[英]Unit Testing Services in AngularJS with Jasmine, Karma and ng-Mock
I'm having trouble accessing my services and filters in unit tests (I haven't tried directives yet).我无法在单元测试中访问我的服务和过滤器(我还没有尝试过指令)。 I've written unit tests before, but as I have moved to the configuration of our builds, I'm having trouble accessing our new services to write unit tests.
我以前写过单元测试,但是当我开始配置我们的构建时,我无法访问我们的新服务来编写单元测试。 I'm continually getting
TypeError: null is not an object (evaluating 'currentSpec.$modules') in...
.我不断收到
TypeError: null is not an object (evaluating 'currentSpec.$modules') in...
。 I did some reading and it looks like it may have to do with the node packages I'm using.我做了一些阅读,看起来它可能与我正在使用的节点包有关。 I was wondering if the greater community could make sure these configurations look correct.
我想知道更大的社区是否可以确保这些配置看起来正确。 I've abbreviated the files below.
我已经缩写了下面的文件。
With the current config, this is erroring out.使用当前配置,这是错误的。
package.json包.json
"devDependencies": {
"angular": "1.5.7",
"angular-mocks": "1.5.7",
"jasmine": "2.4.1",
"jasmine-core": "2.4.1",
"karma-browserify": "5.1.0",
"karma-chrome-launcher": "1.0.1",
"karma-jasmine": "1.0.2",
"karma-nyan-reporter": "0.2.4",
"karma-phantomjs2-launcher": "0.5.0",
"phantomjs2": "2.2.0"
}
karma.conf.js业力.conf.js
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'app/main.js',
'app/modules/**/*.spec.js',
'app/shared/**/**/*.spec.js'
],
preprocessors: {
'app/main.js': ['browserify'],
'app/modules/index.js': ['browserify'],
'app/shared/index.js': ['browserify'],
'app/modules/**/*.spec.js': ['browserify'],
'app/shared/**/**/*.spec.js': ['browserify']
},
})
}
service.spec.js服务规范.js
describe('Unit: Services', function() {
require('angular-mocks/ngMock');
var APIHelper;
beforeEach(function() {
angular.mock.module('app.common.services');
});
beforeEach(inject(function(apiHelperService) {
APIHelper = apiHelperService; //injection is what's breaking
}));
it('should exist', function() {
expect(APIHelper).toBeDefined();
});
});
The services and specs are being loaded and in the correct order.正在以正确的顺序加载服务和规范。 This service has no dependencies.
该服务没有依赖关系。 I'm assuming I'll be getting the same errors when I need to inject service dependencies, but if I can get the injections figured out, I can inject the proper services as I need them.
我假设当我需要注入服务依赖项时我会遇到同样的错误,但如果我能弄清楚注入,我可以根据需要注入正确的服务。
// This worked in a controller
angular.mock.inject(function GetDependencies(service) {
service = service;
});
Thank you in advance for taking the time to look over this and potentially answering a question.提前感谢您抽出时间查看此问题并可能回答问题。
-W -W
I wasn't including require('angular-mocks/ngMock')
in my app declaration.我的应用声明中没有包含
require('angular-mocks/ngMock')
。 Sometimes, it's the little things.有时,这是小事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.