mercredi 18 avril 2018

How to mock an @injected service when testing an angular 2 component?

I have a component with the signature:

constructor(private loremApiService: LoremApiService,
      private ipsumService: IpsumService,
      private dolorService: DolorService,
      @Inject('sitService') private sitService: library.service.Service) {
}

The spec file for the component is set up with:

let component: PowerBiReportComponent; let fixture: ComponentFixture; const mockLoremApi = { methodThatIsCalled: () => {} }; const mockIpsumService = { }; const mockSitService = { };

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [ TestingComponent ],
        schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
        providers: [
            { provide: LoremApiService, useValue: mockLoremApi },
            { provide: IpsumService, useValue: mockIpsumService },
            UnmockedService,
            { provide: library.service.Service, useValue: mockSitService }
        ]
    })
    .compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(TestingComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

However, the provider is not used, due to the @Inject decorator, the test is failing on run with:

Error: StaticInjectorError(DynamicTestModule)[sitService]: 
  StaticInjectorError(Platform: core)[sitService]: 
  NullInjectorError: No provider for sitService!

How do I force the TestingModule to use the mockSitService despite it being @Injected in the component?

Aucun commentaire:

Enregistrer un commentaire