【问题标题】:angularjs: how to mock $rootScope in unit testangularjs:如何在单元测试中模拟 $rootScope
【发布时间】:2013-11-14 12:20:13
【问题描述】:

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

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
    ....

【问题讨论】:

标签: javascript unit-testing angularjs mocking


【解决方案1】:

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

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

您可以拥有多个beforeEach,因此只需在现有beforeEach 上方添加一个即可。

【讨论】:

  • 但由于某种原因你不能这样做: beforeEach(inject(function ($rootScope, $provide) { ... }
猜你喜欢
  • 1970-01-01
  • 2015-04-01
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 2014-02-08
  • 2017-09-25
  • 2014-05-08
  • 1970-01-01
相关资源
最近更新 更多