ReferenceError: module is not defined - Karma/Jasmine configuration with Angular/Laravel app

前端 未结 4 1049

I have an existing Angular/Laravel app in which Laravel acts as an API to the angular frontend serving only JSON data. The page that loads the angular app, index.php

4条回答
  •  悲&欢浪女
    2021-02-05 00:14

    Perhaps this will help someone.

    The solution, for me, was to make sure angular-mocks.js was loaded before my tests. If you're not sure, you control the order in karma.conf.js under the following section:

    // list of files / patterns to load in the browser
    files: [
    // include files / patterns here
    

    Next, to get my test to actually load my angular app, I had to do the following:

    describe("hello world", function() {
        var $rootScope;
        var $controller;
        beforeEach(module("YourAppNameHere"));
        beforeEach(inject(function($injector) {
    
            $rootScope = $injector.get('$rootScope');
            $controller = $injector.get('$controller');
            $scope = $rootScope.$new();
    
        }));
        beforeEach(inject(function($controller) {
            YourControllerHere = $controller("YourControllerHere");
    
        }));
    
        it("Should say hello", function() {
            expect(YourControllerHere.message).toBe("Hello");
        });
    
    });
    

    And in your controller,

    app.controller('YourControllerHere', function() {
    
        this.message = "Hello";
    
    });
    

    Also, another way:

    describe("YourControllerHere", function() {
        var $scope;
        var controller;
    
        beforeEach(function() {
    
            module("YourAppNameHere");
    
            inject(function(_$rootScope_, $controller) {
    
                $scope = _$rootScope_.$new();
                controller = $controller("YourControllerHere", {$scope: $scope});
    
            });
    
        });
    
        it("Should say hello", function() {
            expect(controller.message).toBe("Hello");
        });
    
    });
    

    Enjoy testing!

提交回复
热议问题