How override Provider in Angular 5 for only one test?

前端 未结 5 1192
礼貌的吻别
礼貌的吻别 2020-12-17 08:24

In one of my unit test files, I have to mock several times the same service with different mocks.

import { MyService } from \'../services/myservice.service\'         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 08:40

    If the service is injected as public property, e.g.:

    @Component(...)
    class MyComponent {
      constructor(public myService: MyService)
    }
    

    You can do something like:

    it('...', () => {
      component.myService = new MockMyService2(...); // Make sure to provide MockMyService2 dependencies in constructor, if it has any.
      fixture.detectChanges();
    
      // Your test here...
    })
    

    If injected service is stored in a private property, you can write it as (component as any).myServiceMockMyService2 = new MockMyService2(...); to bypass TS.

    It's not pretty but it works.

    As for TestBed.overrideProvider, I had no luck with that approach (which would be much nicer if it worked):

    it('...', () =>{
      TestBed.overrideProvider(MyService, { useClass: MockMyService2 });
      TestBed.compileComponents();
      fixture = TestBed.createComponent(ConfirmationModalComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    
      // This was still using the original service, not sure what is wrong here.
    });
    

提交回复
热议问题