想通了,我想我会回答我自己的问题。上面的大错误是使用angular.module而不是angular.mock.module,这是通过angular-mock作为模块引用的便利。他们根本不是一回事!
此外,只要在初始化待测模块之前进行初始化,就可以使用angular.mock.module初始化模拟服务。没有必要像上面链接的问题中所建议的那样,将这些模块封装在第三个模块中。即:
describe("Test Service", function() {
var TestService, getvaluestub;
beforeEach(function() {
// create mock service
var mock = {getvalue:function(){}}
angular.module('dependencymodule',[])
.service('dependencyservice',function() {
return mock;
});
//mock the function we are stubbing, (that, in this case, returns value 4)
getvaluestub = sinon.stub(mock,'getvalue')returns(4);
//instantiate your mock service
module('dependencymodule');
//instantiate the module of the service under test,
//that depends on 'dependencyservice' mocked above
//(ie - testmodule includes the service 'testservice')
module('testmodule');
//inject your test service for testing
inject(function ($injector) {
TestService = $injector.get('testservice');
})
//tests go here.....
如果相关模块已经存在,你既可以依然做到以上的,或者你可以获取从$喷油器的服务,将您的间谍和存根,以及>然后<实例化被测服务。间谍/存根的设置> <的依赖服务实例化之前很重要,否则它将在没有它们的情况下被实例化。它看起来像这样:
describe("Test Service", function() {
var TestService, DependencyService, getvaluestub;
beforeEach(function() {
// these modules are specified in the application
module('dependencymodule');
module('testmodule');
inject(function ($injector) {
DependencyService = $injector.get('testservice');
getvaluestub = sinon.stub(DependencyService,'getvalue').returns(4);
OtherService = $injector.get('otherservice');
})
});
// test go here
所以,你去了。希望这对搜索'将模拟注入角度服务'的人有用。
非常感谢您的支持!以下是使用存根进行服务测试服务,控制器和过滤器的另一个示例。 https://gist.github.com/clouddueling/11188718 –