本文介绍了在单元测试 AngularJS 服务时注入依赖服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试服务 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).

我看过这个问题,但我的情况有点不同,因为在我看来,mock 服务 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();
  });
});

我得到的错误是:

错误:未知提供者:serviceBProvider

我怎么能做这样的事情?

How could I do something like this?

推荐答案

实际上在 AngularJS 依赖注入中使用最后获胜"规则.因此,您可以在包含模块和依赖项之后在测试中定义您的服务,然后当您正在测试的服务 A 将使用 DI 请求服务 B 时,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 服务时注入依赖服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 16:39