想通了,我想我會回答我自己的問題。上面的大錯誤是使用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 –