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

Angular 提供服务的组件的角度2测试规范,angular,jasmine,Angular,Jasmine,我使用的是Angular 2 final(2.0.1)。 我有一个提供服务的组件。它是唯一一个使用它的模块,这就是为什么它提供它而不是包含它的模块,并且它也被注入到构造函数中 @Component({ selector: 'my-comp', templateUrl: 'my-comp.component.html', styleUrls: ['my-comp.component.scss'], providers: [MyService], }) export

我使用的是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) {
    }
}
当我尝试实现规范时,它失败了

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

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

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


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

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

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

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


在回答这个问题时,我很容易忽略了使用fixture.debugElement.injector.get在测试中获得服务而不是使用测试床的重要性。