Jasmine 不注入服务
Jasmine doesn't inject services
前提:我的应用程序运行良好,但无论如何我决定实施单元测试。
我的测试,即检查给定对象的服务是否定义失败。
这是我的服务代码:
//app/components/lib/search.js
angular.module("search", ["lazyLoad", "httpInterceptor"])
.service("SearchObject", ['$rootScope', '$location', 'Globals', function ($rootScope, $location, Globals) {
'use strict';
var obj,
SearchObjectPrototype = {};
SearchObjectPrototype.clone = function (source) {
var prop;
for (prop in this) {
if (this.hasOwnProperty(prop)) {
this[prop] = source[prop] || null;
}
}
};
//Definizione SearchObject
obj = Object.create(SearchObjectPrototype, {
q : {value: null, writable: true, enumerable: true},
max_id : {value: null, writable: true, enumerable: true},
next_results : {value: null, writable: true, enumerable: true},
query_debug : {value: null, writable: true, enumerable: true}
});
Object.preventExtensions(obj);
this.getInstance = function () {
return obj;
};
}])
这是我的测试代码:
console.log(1);
describe('search module', function() {
console.log(2);
beforeEach(module('search'));
describe('SearchObject test', function() {
console.log(3);
var SearchObject;
beforeEach(inject(function(_SearchObject_){
console.log(4);
// The injector unwraps the underscores (_) from around the parameter names when matching
SearchObject = _SearchObject_;
}));
it('should evaluate the injected SearchObject', function (){
console.log(5);
expect(SearchObject).toBeDefined()
});
});
});
这是我的 karma.conf.js
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-10-20 using
// generator-karma 1.0.0
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
// as well as any additional frameworks (requirejs/chai/sinon/...)
frameworks: [
"jasmine"
],
// list of files / patterns to load in the browser
files: [
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-ui-router/release/angular-ui-router.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/ngInfiniteScroll/build/ng-infinite-scroll.js',
'bower_components/Chart.js/Chart.js',
'bower_components/angular-chart.js/dist/angular-chart.js',
'bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
'bower_components/angular-mocks/angular-mocks.js',
// endbower
"app/components/lib/search.js",
// "test/mock/**/*.js",
"test/spec/search.js"
],
// list of files / patterns to exclude
exclude: [
],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
"PhantomJS"
],
// Which plugins to enable
plugins: [
"karma-chrome-launcher",
"karma-phantomjs-launcher",
"karma-jasmine"
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
这是我的 Karma 输出
Running "karma:unit" (karma) task
11 02 2016 11:55:43.447:INFO [karma]: Karma v0.13.19 server started at http://lo
calhost:8080/
11 02 2016 11:55:43.474:INFO [launcher]: Starting browser PhantomJS
11 02 2016 11:55:46.510:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on s
ocket /#OphIJTNigEfxY1NIAAAA with id 56068342
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 1
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 2
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 3
LOG: 5
PhantomJS 2.1.1 (Windows 8 0.0.0) test sul modulo search SearchObject test shoul
d evaluate the injected SearchObject FAILED
C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular/angular.j
s:4459:53
forEach@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular/a
ngular.js:340:24
loadModules@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angul
ar/angular.js:4419:12
createInjector@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/an
gular/angular.js:4344:22
workFn@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular-mo
cks/angular-mocks.js:2428:60
**Expected undefined to be defined.**
C:/Users/Rick/Sviluppo/socialsider-fe/test/spec/search.js:19:45
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.043 se
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.019 secs
/ 0.043 secs)
如您所见,log(4)
位于 SearchObject
赋值的同一块中,但未被调用。对象未定义,测试失败。
谁能解释一下为什么?可能是依赖问题?
我发现您需要自己注入 services/factories:
beforeEach(function() {
module('search'));
inject(function(_SearchObject_) {
SearchObject = _SearchObject_;
});
});
这应该使服务可用于测试。我刚回去抽查了一些我自己的测试,发现这是我所有工厂和服务测试的共同部分。
更新:
经过进一步审查,这里发生了一些非常奇怪的事情,可能还有多个问题需要解决。我没有你所有的依赖库,如果不模拟或删除 lazyLoad 和 httpInterceptor,angular 模块根本不会在测试中加载。不过,我假设这不是您的问题并且模块会加载。在那之后,一旦我模拟了 Globals,它就可以正常加载了。
所以简而言之,请确保您正确地为测试提供了 lazyLoad、httpInterceptor 和 Globals,无论是使用实际代码还是通过模拟,测试都会通过。至少对我来说是这样。
前提:我的应用程序运行良好,但无论如何我决定实施单元测试。 我的测试,即检查给定对象的服务是否定义失败。
这是我的服务代码:
//app/components/lib/search.js
angular.module("search", ["lazyLoad", "httpInterceptor"])
.service("SearchObject", ['$rootScope', '$location', 'Globals', function ($rootScope, $location, Globals) {
'use strict';
var obj,
SearchObjectPrototype = {};
SearchObjectPrototype.clone = function (source) {
var prop;
for (prop in this) {
if (this.hasOwnProperty(prop)) {
this[prop] = source[prop] || null;
}
}
};
//Definizione SearchObject
obj = Object.create(SearchObjectPrototype, {
q : {value: null, writable: true, enumerable: true},
max_id : {value: null, writable: true, enumerable: true},
next_results : {value: null, writable: true, enumerable: true},
query_debug : {value: null, writable: true, enumerable: true}
});
Object.preventExtensions(obj);
this.getInstance = function () {
return obj;
};
}])
这是我的测试代码:
console.log(1);
describe('search module', function() {
console.log(2);
beforeEach(module('search'));
describe('SearchObject test', function() {
console.log(3);
var SearchObject;
beforeEach(inject(function(_SearchObject_){
console.log(4);
// The injector unwraps the underscores (_) from around the parameter names when matching
SearchObject = _SearchObject_;
}));
it('should evaluate the injected SearchObject', function (){
console.log(5);
expect(SearchObject).toBeDefined()
});
});
});
这是我的 karma.conf.js
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-10-20 using
// generator-karma 1.0.0
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
// as well as any additional frameworks (requirejs/chai/sinon/...)
frameworks: [
"jasmine"
],
// list of files / patterns to load in the browser
files: [
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-ui-router/release/angular-ui-router.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/ngInfiniteScroll/build/ng-infinite-scroll.js',
'bower_components/Chart.js/Chart.js',
'bower_components/angular-chart.js/dist/angular-chart.js',
'bower_components/bootstrap-sass/assets/javascripts/bootstrap.js',
'bower_components/angular-mocks/angular-mocks.js',
// endbower
"app/components/lib/search.js",
// "test/mock/**/*.js",
"test/spec/search.js"
],
// list of files / patterns to exclude
exclude: [
],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
"PhantomJS"
],
// Which plugins to enable
plugins: [
"karma-chrome-launcher",
"karma-phantomjs-launcher",
"karma-jasmine"
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
这是我的 Karma 输出
Running "karma:unit" (karma) task
11 02 2016 11:55:43.447:INFO [karma]: Karma v0.13.19 server started at http://lo
calhost:8080/
11 02 2016 11:55:43.474:INFO [launcher]: Starting browser PhantomJS
11 02 2016 11:55:46.510:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on s
ocket /#OphIJTNigEfxY1NIAAAA with id 56068342
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 1
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 2
PhantomJS 2.1.1 (Windows 8 0.0.0) LOG: 3
LOG: 5
PhantomJS 2.1.1 (Windows 8 0.0.0) test sul modulo search SearchObject test shoul
d evaluate the injected SearchObject FAILED
C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular/angular.j
s:4459:53
forEach@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular/a
ngular.js:340:24
loadModules@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angul
ar/angular.js:4419:12
createInjector@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/an
gular/angular.js:4344:22
workFn@C:/Users/Rick/Sviluppo/socialsider-fe/bower_components/angular-mo
cks/angular-mocks.js:2428:60
**Expected undefined to be defined.**
C:/Users/Rick/Sviluppo/socialsider-fe/test/spec/search.js:19:45
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.043 se
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.019 secs
/ 0.043 secs)
如您所见,log(4)
位于 SearchObject
赋值的同一块中,但未被调用。对象未定义,测试失败。
谁能解释一下为什么?可能是依赖问题?
我发现您需要自己注入 services/factories:
beforeEach(function() {
module('search'));
inject(function(_SearchObject_) {
SearchObject = _SearchObject_;
});
});
这应该使服务可用于测试。我刚回去抽查了一些我自己的测试,发现这是我所有工厂和服务测试的共同部分。
更新: 经过进一步审查,这里发生了一些非常奇怪的事情,可能还有多个问题需要解决。我没有你所有的依赖库,如果不模拟或删除 lazyLoad 和 httpInterceptor,angular 模块根本不会在测试中加载。不过,我假设这不是您的问题并且模块会加载。在那之后,一旦我模拟了 Globals,它就可以正常加载了。
所以简而言之,请确保您正确地为测试提供了 lazyLoad、httpInterceptor 和 Globals,无论是使用实际代码还是通过模拟,测试都会通过。至少对我来说是这样。