由于注入(inject)器未正确注入(inject),我在单元测试 angularJS 时遇到了困难。我注入(inject)的任何内容结果都是 undefined
。
模块:
app.module.js
angular.module('myServices', []);
AngularTest.js
describe('AngularTest', function() {
beforeEach(module('myServices'));
var scope;
beforeEach(inject(function(_$rootScope_) {
// The injector unwraps the underscores (_) from around the parameter names when matching
scope = _$rootScope_;
}));
describe('Testing Angular injection', function() {
it('scope should be defined', function() {
expect(scope).toBeDefined(); // fails
});
});
});
我已经成功地在我的主模块中测试了 Controller ,但是,这个特定的模块正在测试我的理智。
有什么想法吗?
编辑:
业力文件:
files: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-resource/angular-resource.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-animate/angular-animate.js',
'app/bower_components/angular-cookies/angular-cookies.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/app.module.js',
'app/components/**/controller/*.js',
'app/components/**/model/*.js',
'app/components/**/test/unit/*.js'
]
服务模块在app.module.js
中定义,服务在app/components/services/model/myService.js
(路径似乎不合逻辑,我试图抽象我的结构以尽可能概括这个问题)
编辑 2:
Karma 似乎也没有提示:来自日志:
28 08 2015 03:38:47.095:WARN [karma]: No captured browser, open http://localhost:9876/
28 08 2015 03:38:47.107:INFO [karma]: Karma v0.13.9 server started at http://localhost:9876/
28 08 2015 03:38:47.151:INFO [launcher]: Starting browser Safari
28 08 2015 03:38:54.790:INFO [Safari 8.0.6 (Mac OS X 10.10.3)]: Connected on socket jhi7nBcWAV_vCJkMAAAA with id 68159057
后面是失败的测试用例:
Safari 8.0.6 (Mac OS X 10.10.3) AngularTest Testing Angular injection scope should be defined FAILED
/path/to/project/app/bower_components/angular/angular.js:68:32
forEach@/path/to/project/app/bower_components/angular/angular.js:336:24
loadModules@/path/to/project/app/bower_components/angular/angular.js:4369:12
createInjector@/path/to/project/app/bower_components/angular/angular.js:4294:22
workFn@/path/to/project/app/bower_components/angular-mocks/angular-mocks.js:2390:60
/path/to/project/app/bower_components/angular/angular.js:4408:30
Expected undefined to be defined.
/path/to/project/app/components/services/test/unit/AngularTest.js:16:34
最佳答案
该死的 SAFARI!
解决方案:在 karma 配置文件中将浏览器更改为 Chrome,调试日志会输出更详细的错误信息!
原来我没有在我的业力 文件
中包含所需的模块依赖项。
关于javascript - AngularJS 单元测试 : Injected Services undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32261905/