提供服务的组件的Angular 2测试规范 [英] Angular 2 test spec for a component that provides a service

查看:85
本文介绍了提供服务的组件的Angular 2测试规范的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 2 final(2.0.1)。
我有一个提供服务的组件。它是唯一使用它的人,这就是为什么它提供它而不是包含模块,它也被注入到构造函数中。

I am using Angular 2 final (2.0.1). I have a component that provides a service. It is the only one that uses it, this is why it provides it and not the containing module and it is also being injected into the constructor.

@Component({
    selector: 'my-comp',
    templateUrl: 'my-comp.component.html',
    styleUrls: ['my-comp.component.scss'],
    providers: [MyService],
})
export class MyComponent {

    constructor(private myService: MyService) {
    }
}

当我尝试实施规范时,它失败了。

When I try to implement the spec, it fails.

describe("My Component", () => {

beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [
            {
                provide: MyService,
                useClass: MockMyService
            },
        ]
    });

    this.fixture = TestBed.createComponent(MyComponent);
    this.myService = this.fixture.debugElement.injector.get(MyService);

});

describe("this should pass", () => {

    beforeEach(() => {
        this.myService.data = [];
        this.fixture.detectChanges();
    });

    it("should display", () => {
        expect(this.fixture.nativeElement.innerText).toContain("Health");
    });

});

但是,当我将服务提供声明从组件移动到包含模块时,测试通过。

but, when I move the service provide declaration from the component to the containing module, the tests passes.

我认为这是因为TestBed测试模块定义了模拟服务,但是当创建组件时 - 它会用实际的实现覆盖模拟......

I assume it is because the TestBed testing module defines the mock service, but when the component is created - it overrides the mock with the actual implementation...

有没有人知道如何测试提供服务并使用模拟服务的组件?

Does anyone have any idea how to test a component that provides a service and use a mock service?

推荐答案

您需要覆盖 @ Component.providers ,因为它优先于您通过测试床配置提供的任何模拟。

You need to override the @Component.providers, as it has precedence over any mock you provide through the test bed config.

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [MyComponent]
  });

  TestBed.overrideComponent(MyComponent, {
    set: {
      providers: [
        { provide: MyService, useClass: MockMyService }
      ]
    }
  }); 
});

另见:

  • Override Component Providers

这篇关于提供服务的组件的Angular 2测试规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆