Angular mock fails to inject my module dependencies

扶醉桌前 提交于 2019-12-05 01:56:01

My problem was in fact due to a little mistake in karma.conf.js. Indeed, my application is defined as follow:

var fooApp = angular.module('fooApp', [ 'ngRoute', 'ngAnimate', 'hmTouchEvents' ]);

and my karma.conf.js loads the following scripts:

files: [
    'app/bower_components/angular/angular.min.js',
    'app/bower_components/angular-route/angular-route.min.js',
    'app/bower_components/hammerjs/hammer.min.js',
    'app/bower_components/angular-hammer/angular-hammer.js',
    'app/bower_components/angular-mocks/angular-mocks.js',

    'app/js/foo-application.js',
    'app/js/foo-controllers.js',
    'app/js/foo-services.js',
    'app/js/foo-router.js',

    'test/jasmine/*.js'
], ...

but the module ngAnimate was not loaded. So I just added that line:

    'app/bower_components/angular-animate/angular-animate.min.js',

and it works!

You are redefining fooApp module in the test.

You need to load it with Angular in the test code like this:

angular.mock.module('ngRoute', 'ngAnimate', 'hmTouchEvents', 'fooApp');

Try like this:

describe('MainController test', function () {
    var scope;
    var controller;

    beforeEach(angular.mock.module('fooApp'));
    beforeEach(angular.mock.inject(function($rootScope, $controller) {
        scope = $rootScope.$new();
        controller = $controller('MainCtrl', {
            $scope: scope
        });
    });
    it('should display a list', function () {
        console.log('-------------- Run Test 1 | ' + scope);
        expect(scope.currentStep).toBe(1);
    });
});

The thing, you need to understand, is if you declare some module with its dependencies(like angular.module('fooApp', [ 'ngRoute', 'ngAnimate', 'hmTouchEvents' ])), when you inject the module(fooApp) on your tests, you don't need to inject the dependency modules either.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!