想通了这一点,我想我会回答我自己的问题。上面的大错误是使用 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.....
如果依赖模块已经存在,您仍然可以执行上述所有操作,或者您可以从 $injector 获取服务,插入您的间谍和存根,然后>实例化被测服务。重要的是,间谍/存根的设置>之前<依赖服务被实例化,否则它将在没有它们的情况下被实例化。它看起来像这样:
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
所以,你去吧。希望这对搜索“将模拟注入角度服务”的人有用。