繁体   English   中英

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

[英]angularjs: how to mock $rootScope in unit test

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

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

    }));
    ....
}));

但是,当我如上所述执行“ inject(function($ 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
    ....

我认为在调用describe时注入不起作用。 我遇到了相同的错误,可以通过将注入从我的describe调用移到beforeEach调用来解决:

var rootScope;
beforeEach(inject(function ($rootScope) {
    rootScope = $rootScope.$new();
}));

您可以有多个beforeEach ,因此只需在现有的beforeEach之上添加一个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM