我有一个基本的第三方服务,我正在尝试对其进行单元测试。我无法将其发送到throwError
。
示例
angular.module('example')
.factory('exampleFactory', ['$window', function($window) {
if(typeof $window.examplePlugin === 'undefined') {
throw new Error('plugin not available');
} else {
return $window.examplePlugin;
}
}]);
单元测试
describe('Factory', function() {
var $window, exampleFactory;
beforeEach(module('example'));
beforeEach(function() {
module(function($provide) {
$provide.value('$window', {});
});
inject(function(_$window_, _exampleFactory_) {
exampleFactory = _exampleFactory_;
$window = _$window_;
});
});
it('should exist', function() {
$window.examplePlugin = {};
expect($window.examplePlugin).toBeDefined();
});
it('should throw an error', function() {
function fn() { delete $window.examplePlugin; }
expect(fn).toThrowError();
});
});
答案 0 :(得分:0)
鉴于你所展示的内容,我只能想到这个
describe('Factory', function() {
var $window;
beforeEach(module('example', function($provide) {
$provide.value('$window', $window = {});
});
it('returns examplePlugin if it is set', function() {
$window.examplePlugin = 'foo';
inject(function(exampleFactory) {
expect(exampleFactory).toBe($window.examplePlugin);
});
});
it('throws an error if examplePlugin is not set', function() {
// not entirely sure I have this wrapped correctly
// but trial and error should get you there
expect(function() {inject(function(exampleFactory) {})}).toThrow();
});
});
主要的是你需要在注射工厂之前设置所需的$window
属性。