Jasmine无法实例化Angular模块?

时间:2015-12-24 17:02:27

标签: javascript angularjs unit-testing jasmine

好的,我正在尝试使用Jasmine 2.2.0为AngularJS项目实现单元测试 - 而且我无法为控制器进行基本的示例测试。任何帮助表示赞赏。

以下是控制器的代码(我最简单的代码):

angular.module('app.alerts')
    .controller('AlertCtrl', AlertCtrl);

AlertCtrl.$inject = ['$scope', 'AlertService'];

function AlertCtrl($scope, AlertService) {

    var vm = this;
    vm.closeAlert = function(index) {
        AlertService.closeAlert(index);
    }

    vm.getAlertList = function() {
        return AlertService.getAlertList();
    }
}

这是我试图运行的spec文件:

describe('myApp', function() {
    describe('controller', function() {

        var scope, controller;
        var mockAlertService = {      // simple mock service
            closeAlert: function(e) {
                console.log('close');
            },
            getAlertList: function() {
                return [];
            }
        }    

        beforeEach(function() {
            angular.mock.module('app.alert');
        });

        beforeEach(inject(function($rootScope, $controller) {
            scope = $rootScope.$new();
            controller = $controller('AlertCtrl as alertctrl', {
                $scope: scope,
                AlertService: mockAlertService
            });
        }));

        it('should work: ', function() {
            expect(true).toBe(true);
        });
    });
});

当我运行测试时,我收到以下错误消息:

Error: [$inject:modulerr] Failed to instantiate module app.alert due to:
[$injector:nomod] Module 'app.alert' is not available! You either misspelled
the module name or forgot to load it.

注射器似乎并不知道app.alert模块,这意味着它没有被正确模拟?我在我的SpecRunner.html文件中包含angular-mocks.js文件。谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:1)

你没有拼错app.alertapp.alerts

angular.module('app.alerts')
    .controller('AlertCtrl', AlertCtrl);

angular.mock.module('app.alert');