angularjs – 注入模拟角度服务依赖关系

前端之家收集整理的这篇文章主要介绍了angularjs – 注入模拟角度服务依赖关系前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个服务,“输入”,在模块“Puts”中定义,这取决于第二个服务’InputCreator’.为了测试Inputs服务,我需要存放InputCreator服务.

据了解answer here,我应该创建一个包含我的存根服务的模块,然后创建一个新的“测试”模块,指定被测试模块,然后将存根模块指定为依赖关系.然后从喷油器拉出服务.像这样:

  1. beforeEach(function() {
  2.  
  3. angular.module.('Puts'); // contains the service 'Inputs'
  4.  
  5. angular.module('Mocks',[])
  6. .service('InputCreator',function(){
  7. var mockInputs = {
  8. //stubbed behavIoUr goes here
  9. };
  10. return mockInputs;
  11. });
  12. });
  13.  
  14. angular.module('Test',['Puts','Mocks'];
  15.  
  16. inject(function($injector){
  17. Inputs = $injector.get('Inputs');
  18. });
  19. });

然而,注射器功能以“未知输入提供者”输入进行响应.

我误入歧途?

谢谢!

想到这一点,我以为我会回答我自己的问题.上面的大错误是使用angular.module而不是angular.mock.module,这是以角度模拟作为模块引用的方便.他们根本不一样!

另外,只要在初始化测试模块之前,只要使用angular.mock.module初始化模拟服务即可.在上面提到的问题中,没有必要将这个“将模块包装在第三个模块”中.以机智:

  1. describe("Test Service",function() {
  2. var TestService,getvaluestub;
  3.  
  4. beforeEach(function() {
  5.  
  6. // create mock service
  7. var mock = {getvalue:function(){}}
  8.  
  9. angular.module('dependencymodule',[])
  10. .service('dependencyservice',function () {
  11. return mock;
  12. });
  13.  
  14. //mock the function we are stubbing,(that,in this case,returns value 4)
  15. getvaluestub = sinon.stub(mock,'getvalue')returns(4);
  16.  
  17. //instantiate your mock service
  18. module('dependencymodule');
  19.  
  20. //instantiate the module of the service under test,//that depends on 'dependencyservice' mocked above
  21. //(ie - testmodule includes the service 'testservice')
  22. module('testmodule');
  23.  
  24. //inject your test service for testing
  25. inject(function ($injector) {
  26. TestService = $injector.get('testservice');
  27. })
  28.  
  29. //tests go here.....

如果依赖关系模块已经存在,您可以仍然执行上述所有操作,或者您可以从$注射器获取服务,插入间谍和存根,然后>实例化被测服务.重要的是,间隔/存根在<依赖服务被实例化,或者没有它们将被实例化.看起来像这样:

  1. describe("Test Service",DependencyService,getvaluestub;
  2.  
  3. beforeEach(function() {
  4.  
  5. // these modules are specified in the application
  6. module('dependencymodule');
  7. module('testmodule');
  8.  
  9. inject(function ($injector) {
  10. DependencyService = $injector.get('testservice');
  11.  
  12. getvaluestub = sinon.stub(DependencyService,'getvalue').returns(4);
  13.  
  14. OtherService = $injector.get('otherservice');
  15. })
  16. });
  17.  
  18. // test go here

所以,你去了.希望这对于搜索“注入角度服务”的人是有用的.

猜你在找的Angularjs相关文章