是否有可能在Angular连接的业力测试中监视某项服务?
示例:myService
是被测单位。 thirdParty
代表应该监视的第三方服务。
.service('thirdParty', function() {
return {
hello: function() {
return 'hello world';
}
}
})
.service('myService', function(thirdParty) {
return {
world: function() {
return thirdParty.hello();
}
}
})
在我的业力测试中,我想监视thirdParty
服务并致电真实服务:
describe('spy', function() {
var thirdParty, myService;
beforeEach(inject(function(_thirdParty_, _myService_) {
myService = _myService_;
thirdParty = _thirdParty_;
spyOn(thirdParty, 'hello').andCallThrough();
}));
it('should be called in myService', function() {
expect(thirdParty.hello).toHaveBeenCalled();
expect(myService.world()).toBe('hello world');
});
})
重点是我的测试应断言
myService
myService.world()
断言正常,但正如我所料,myService
无法对间谍thirdParty
服务进行操作。
结果是:
Expected spy hello to have been called.
在某些测试中,我已经使用provider
和裸模拟来嘲笑第三方服务。
因此,我尝试创建cacheFactory
附带beforeEach(module('angular-cache'));
beforeEach(module(function($provide, $injector, CacheFactoryProvider) {
//CacheFactoryProvider requires $q service
var q = $injector.get('$q');
var cacheFactory = CacheFactoryProvider.$get[1](q);
spyOn(cacheFactory, 'createCache').andCallThrough();
$provide.factory('CacheFactory', cacheFactory);
}));
的间谍实例:
Error: [$injector:modulerr] Failed to instantiate module function ($provide, $injector, CacheFactoryProvider) due to:
Error: [$injector:unpr] Unknown provider: $q
现在我面临着鸡与蛋的问题:
with open(argv[1]) as f:
print(f.readlines())
我知道这个例子不起作用,但是由于缺乏内部知识,Angular实际上是如何实例化和布线服务我想问社区我的测试方法是否可行甚至是理智的。谢谢你的帮助。
答案 0 :(得分:0)
而不是
it('should be called in myService', function() {
expect(thirdParty.hello).toHaveBeenCalled();
expect(myService.world()).toBe('hello world');
});
测试应该是
it('should be called in myService', function() {
expect(myService.world()).toBe('hello world');
expect(thirdParty.hello).toHaveBeenCalled();
});
实际上,在您实际调用thirdParty.hello
之前,系统不会调用myService.world()
方法。