AngularJS中的测试:注入函数的参考错误

时间:2013-02-07 22:52:24

标签: javascript angularjs testing karma-runner

我尝试测试下面的代码:

describe('myService test', function () {
    describe('when I call myService.one', function () {
        beforeEach(angular.module('TargetMarketServices'));
        it('returns 1', inject(function (imagesRepository) {
            expect(true).toEqual(true);
        }));

    });

});

执行此代码时出现此错误:

TypeError: 'undefined' is not a function (evaluating 'this.func.apply(this.spec)')
    at http://localhost:8080/testacular.js:76
    at http://localhost:8080/context.html:35
ReferenceError: Can't find variable: inject
    at /home/peter/Dropbox/AngularJS/set-component/test/sets/sets-ihm.js:6
    at /home/peter/Dropbox/AngularJS/set-component/test/sets/sets-ihm.js:8
    at /home/peter/Dropbox/AngularJS/set-component/test/sets/sets-ihm.js:10

PhantomJS 1.8:执行1 of 3(1失败)(跳过2)(0.072秒/ 0.01秒)

对于我的测试,我将Testacular与Jasmine和PhantomJS一起使用。

2 个答案:

答案 0 :(得分:27)

AngularJS提供了两个测试库:

  • angular-mocks.js
  • 角scenario.js

angular-mocks用于Jasmine和Karma测试。它发布了在您的Jasmine规范测试中使用的全局方法module()和inject()。这意味着您必须加载angular-mocks.js脚本(在加载angular.js库/脚本之后)

angular-scenario仅用于e2e测试。

答案 1 :(得分:13)

你所在的行

beforeEach(angular.module('TargetMarketServices'));

应该是

beforeEach(module('TargetMarketServices'));

如果您查看test / unit / directivesSpec.js中的angular-phonecat项目,它会使用

beforeEach(module('myApp.directives'));

如果我修改它以改为使用angular.module:

beforeEach(angular.module('myApp.directives'));

然后我在运行testacular时遇到此错误:

TypeError: 'undefined' is not a function (evaluating 'this.func.apply(this.spec)')