Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

jasmine - Angular 2 test spec for a component that provides a service

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

See Also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...