angularjs:如何在单元测试中模拟$ rootScope

Jea*_*eri 1 javascript unit-testing mocking angularjs

我有一个看起来像这样的单元测试

describe('Interceptor: myInterceptor', inject(function($rootScope){
    var rootScope, routeParams = { id: null };

    beforeEach(module('MyApp', function ($provide) {
        $provide.factory('$routeParams', function () {   // mock $routeParams
            return routeParams;
        });

        rootScope = $rootScope.$new();
        $provide.value('$rootScope', rootScope);         // mock $rootScope

    }));
    ....
}));
Run Code Online (Sandbox Code Playgroud)

但是,当我执行"注入(函数($ rootScope){.."时,如上所示,我得到以下错误(使用Karma和PhantomJS):

PhantomJS 1.9.2 (Mac OS X) Interceptor: myInterceptor encountered a declaration exception FAILED
TypeError: 'null' is not an object (evaluating 'currentSpec.$modules')
    at workFn (/dev/myapp/app/bower_components/angular-mocks/angular-mocks.js:2072)
    at /dev/myapp/test/spec/interceptors/my-interceptor.js:67
    ....
Run Code Online (Sandbox Code Playgroud)

Ess*_*seb 5

我打电话时不认为注射有效describe.我有同样的错误,我通过将注入从我的describe呼叫转移到呼叫来解决beforeEach:

var rootScope;
beforeEach(inject(function ($rootScope) {
    rootScope = $rootScope.$new();
}));
Run Code Online (Sandbox Code Playgroud)

您可以拥有多个beforeEach,因此只需将此一个添加到您现有的上方即可beforeEach.

  • 但是由于某种原因你无法做到:beforeEach(inject(function($ rootScope,$ provide){...} (2认同)