提供服务的组件的Angular 2测试规范

Sef*_*nio 7 jasmine angular

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

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

    constructor(private myService: MyService) {
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试实现规范时,它失败了.

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");
    });

});
Run Code Online (Sandbox Code Playgroud)

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

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

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

Pau*_*tha 21

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

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

  TestBed.overrideComponent(MyComponent, {
    set: {
      providers: [
        { provide: MyService, useClass: MockMyService }
      ]
    }
  }); 
});
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • 当得出这个答案时,我很容易忽略了使用fixture.debugElement.injector.get在测试中获取服务而不是使用TestBed的重要性。https://angular.io/guide/testing#the-override-tests (2认同)