注射相关的服务时,单元测试AngularJS服务 [英] Injecting dependent services when unit testing AngularJS services
问题描述
我测试服务A,但是服务A依赖于服务B(即服务B被注入到服务A)。
I'm testing service A, but service A depends on service B (i.e. service B is injected into service A).
我见过这个问题但我的情况是不同的一点,因为在我看来,它更有意义模拟的服务B,而不是注射服务B的实际情况我会用茉莉间谍嘲笑它。
I've seen this question but my case is a bit different because in my opinion it makes more sense to mock service B instead of injecting an actual instance of service B. I'd mock it with a jasmine spy.
下面是一个样本测试:
describe("Sample Test Suite", function() {
beforeEach(function() {
module('moduleThatContainsServiceA');
inject([
'serviceA', function(service) {
this.service = service;
}
]);
});
it('can create an instance of the service', function() {
expect(this.service).toBeDefined();
});
});
我得到的错误是:
The error I get is:
错误:未知提供商:serviceBProvider
Error: Unknown provider: serviceBProvider
我怎么会做这样的事情?
How could I do something like this?
推荐答案
其实在AngularJS依赖注射使用'最后的胜的规则。所以,你可以包括你的模块和依赖关系确定后,在测试你的服务,然后当你正在测试将使用DI请求服务B的服务A,AngularJS将会给服务B的嘲笑版本。
Actually in AngularJS Dependency Injection uses the 'last wins' rule. So you can define your service in your test just after including your module and dependencies, and then when service A that you're testing will request service B using DI, AngularJS will give mocked version of service B.
这往往是通过定义像MyAppMocks新的模块完成,把嘲笑服务/价值那里,然后刚刚添加该模块作为依赖关系。
This is often is done by defining new module like MyAppMocks, putting mocked services/values there and then just adding this module as dependency.
的种类(示意图):
beforeEach(function() {
angular.module('MyAppMocks',[]).service('B', ...));
angular.module('Test',['MyApp','MyAppMocks']);
...
这篇关于注射相关的服务时,单元测试AngularJS服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!