How override Provider in Angular 5 for only one test?

前端 未结 5 1193
礼貌的吻别
礼貌的吻别 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:55

    As of angular 6 I noticed that overrideProvider works with the useValue property. So in order to make it work try something like:

    class MockRequestService1 {
      ...
    }
    
    class MockRequestService2 {
      ...
    }
    

    then write you TestBed like:

    // example with injected service
    TestBed.configureTestingModule({
      // Provide the service-under-test
      providers: [
        SomeService, {
          provide: SomeInjectedService, useValue: {}
        }
      ]
    });
    

    And whenever you want to override the provider just use:

    TestBed.overrideProvider(SomeInjectedService, {useValue: new MockRequestService1()});
    // Inject both the service-to-test and its (spy) dependency
    someService = TestBed.get(SomeService);
    someInjectedService = TestBed.get(SomeInjectedService);
    

    Either in a beforeEach() function or place it in an it() function.

提交回复
热议问题