angularjs – 注入模拟角度服务依赖关系
发布时间:2020-12-17 09:27:40 所属栏目:安全 来源:网络整理
导读:我有一个服务,“输入”,在模块“Puts”中定义,这取决于第二个服务’InputCreator’.为了测试Inputs服务,我需要存放InputCreator服务. 据了解answer here,我应该创建一个包含我的存根服务的模块,然后创建一个新的“测试”模块,指定被测试模块,然后将存根模块
|
我有一个服务,“输入”,在模块“Puts”中定义,这取决于第二个服务’InputCreator’.为了测试Inputs服务,我需要存放InputCreator服务.
据了解answer here,我应该创建一个包含我的存根服务的模块,然后创建一个新的“测试”模块,指定被测试模块,然后将存根模块指定为依赖关系.然后从喷油器拉出服务.像这样: beforeEach(function() {
angular.module.('Puts'); // contains the service 'Inputs'
angular.module('Mocks',[])
.service('InputCreator',function(){
var mockInputs = {
//stubbed behaviour goes here
};
return mockInputs;
});
});
angular.module('Test',['Puts','Mocks'];
inject(function($injector){
Inputs = $injector.get('Inputs');
});
});
然而,注射器功能以“未知输入提供者”输入进行响应. 我误入歧途? 谢谢!
想到这一点,我以为我会回答我自己的问题.上面的大错误是使用angular.module而不是angular.mock.module,这是以角度模拟作为模块引用的方便.他们根本不一样!
另外,只要在初始化测试模块之前,只要使用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",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
所以,你去了.希望这对于搜索“注入角度服务”的人是有用的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
