我正在尝试使用以下方法对Angular服务进行单元测试:
angular 1.3.8
angular-mocks 1.3.8
karma 0.13.19
jasmine 2.4.1
node 0.10.33
OS: Windows 7
Browser: PhantomJS 2.1.3
问题是,我希望测试的服务(MyService
)没有被angular-mocks lib注入测试文件中(即'inject'方法什么都不做)。我的代码如下:
(function() {
'use strict';
angular.module('module', [ 'ngCookies', 'ngSanitize' ]);
})();
(function () {
'use strict';
angular.module('module')
.factory('MyService', MyService);
MyService.$inject = ['Dependency'];
function MyService(Dependency) {
return {
method: method
};
function method() {
// do something
}
}
})();
(function () {
'use strict';
describe('MyService', function () {
var deferred;
var MyService;
var DependencyMock = {};
beforeEach(module('module'));
beforeEach(module(function ($provide) {
$provide.value('Dependency', DependencyMock);
}));
beforeEach(inject(function (_MyService_, $q) {
MyService = _MyService_; // nothing is injected here
deferred = $q.defer(); // nothing is injected here
}));
it('should be injected', function () {
console.log(deferred); // logs 'undefined'
expect(MyService).toBeDefined(); // fails
});
describe('method', function () {
it('should have this method', function () {
expect(MyService.method).toBeDefined(); // fails as MyService is undefined
expect(typeof MyService.method).toBe('function');
});
});
});
})();
// list of files / patterns to load in the browser
files: [
'libs/angular/angular.js',
'libs/angular-mocks/angular-mocks.js',
'src/js/main.js',
'src/js/services/service.js',
'src/js/tests/unit/service.spec.js'
]
"devDependencies": {
"bower": "1.7.7",
"grunt": "0.4.5",
"grunt-contrib-clean": "0.7.0",
"grunt-contrib-concat": "0.5.1",
"grunt-contrib-connect": "0.11.2",
"grunt-contrib-copy": "0.8.2",
"grunt-contrib-cssmin": "0.14.0",
"grunt-contrib-jshint": "0.12.0",
"grunt-contrib-less": "1.1.0",
"grunt-contrib-uglify": "0.11.0",
"grunt-karma": "0.12.1",
"grunt-lesshint": "1.1.1",
"grunt-ngdocs": "0.2.9",
"grunt-processhtml": "0.3.9",
"jasmine-core": "2.4.1",
"karma": "0.13.19",
"karma-cli": "0.1.2",
"karma-coverage": "0.5.3",
"karma-jasmine": "0.3.6",
"karma-phantomjs-launcher": "1.0.0",
"karma-spec-reporter": "0.0.24",
"phantomjs-prebuilt": "2.1.3"
}
"devDependencies": {
"angular": "1.3.8",
"angular-animate": "1.3.8",
"angular-cookies": "1.3.8",
"angular-mocks": "1.3.8",
"angular-soap": "2.1.1",
"bootstrap": "3.3.6",
"font-awesome": "4.5.0",
"angular-translate": "2.9.0",
"angular-sanitize": "1.3.8"
}
我的猜测是,这与angular-mocks
有某种关联。
答案 0 :(得分:2)
我已经找到了问题所在。 Karma似乎没有包含其中一个Angular模块依赖项,这导致了'注入'不工作。
答案 1 :(得分:0)
尝试在每个 it()方法中注入服务实例。
例如:
it('should be injected', inject(function ('MyService') {
console.log(deferred);
expect(MyService).toBeDefined();
}));
describe('method', function () {
it('should have this method', inject(function ('MyService') {
expect(MyService.method).toBeDefined();
expect(typeof MyService.method).toBe('function');
}));
});