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

时间:2013-11-14 12:20:14

标签: javascript unit-testing angularjs mocking

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

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

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

然而,当我执行“注入(函数($ 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
    ....

1 个答案:

答案 0 :(得分:5)

我认为在致电describe时注射不起作用。我有同样的错误,我通过将注释从describe电话转移到beforeEach电话来解决:

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

您可以拥有多个beforeEach,因此只需将其添加到现有beforeEach之上。