AngularJS覆盖(模拟)单元测试服务
发布时间:2020-12-17 17:55:39 所属栏目:安全 来源:网络整理
导读:场景非常简单,我试图测试服务A,这取决于服务B,所以我决定在注入服务A之前通过覆盖它来模拟服务B.但是,我也测试服务B,它不再有效因为它被覆盖了.有关如何避免这种情况的任何想法? 应用代码. angular.module('MyApp.services') .factory('serviceB',function(
场景非常简单,我试图测试服务A,这取决于服务B,所以我决定在注入服务A之前通过覆盖它来模拟服务B.但是,我也测试服务B,它不再有效因为它被覆盖了.有关如何避免这种情况的任何想法?
应用代码. angular.module('MyApp.services') .factory('serviceB',function(){ return { greeting: function(){ return 'hello'; } } }) .factory('serviceA',['serviceB',function(serviceB){ return { greeting: function(){ return 'I say: ' + serviceB.greeting(); } }); 单元测试: describe('My app services',function(){ beforeEach(module('MyApp.services')); describe('service A',function(){ // mock service B angular.module('MyApp.services').factory('serviceB',function(){ return { greeting: function(){ return 'mocked B'; } } }); var serviceA; inject(function(_serviceA_){ serviceA = _serviceA_; }); it('should work',function(){ var words = serviceA.greeting(); expect(words).toBe('I say: mocked B'); }); }); describe('service B'. function(){ var serviceB; inject(function(_serviceB_){ serviceB = _serviceB_; }); it('should work',function(){ var words = serviceB.greeting(); expect(words).toBe('hello'); }); }); }); 解决方法
您的服务注入可能应该在beforeEach中或作为测试的一部分,否则我认为它们将在测试开始之前发生或根本不发生,例如
beforeEach(inject(function(_serviceA_){ serviceA = _serviceA_; })); 要么 it('should work',inject(function(serviceA){ var words = serviceA.greeting(); expect(words).toBe('I say: mocked B'); })); 为了解决你实际问的问题,我建议你做两件事之一: >覆盖注入器而不是模块中的服务 beforeEach(module(function($provide){ $provide.value('serviceB',{ greeting: function(){ return 'mocked B'; } }); })); 见plunker. 在某处(只需要调用一次),将新模块的定义包含在您的模拟版本的serviceB中 angular.module('MyApp.services.mock',[]) .factory('serviceB',function(){ return { greeting: function(){ return 'mocked B'; } } }); 然后,您当前在测试模块中更改服务的位置,使用以下内容将模拟加载到顶部. beforeEach(module('MyApp.services.mock')); 见plunker (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |