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

Chr*_*riX 17 javascript testing angularjs 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);
        }));

    });

});
Run Code Online (Sandbox Code Playgroud)

执行此代码时,我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

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

对于我的测试,我使用Testacular与Jasmine和PhantomJS.

小智 27

AngularJS提供了两个测试库:

  • 角mocks.js
  • 角scenario.js

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

angular-scenario仅用于e2e测试.


Rya*_*ill 13

你拥有的那条线

beforeEach(angular.module('TargetMarketServices'));
Run Code Online (Sandbox Code Playgroud)

应该

beforeEach(module('TargetMarketServices'));
Run Code Online (Sandbox Code Playgroud)

如果你看一下它使用的test/unit/directivesSpec.js 中的angular-phonecat项目

beforeEach(module('myApp.directives'));
Run Code Online (Sandbox Code Playgroud)

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

beforeEach(angular.module('myApp.directives'));
Run Code Online (Sandbox Code Playgroud)

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

TypeError: 'undefined' is not a function (evaluating 'this.func.apply(this.spec)')
Run Code Online (Sandbox Code Playgroud)

  • 但是,当我只使用模块时,我收到错误"ReferenceError:找不到变量:模块" (3认同)
  • 如何更新和接受答案?我有同样的问题,这有助于我解决它. (3认同)