In my Angular app I have a service which is provided at a component level:
@Component({
selector: 'my-component',
templateUrl: './my.component.html',
providers: [MyService],
})
export class MyComponent implements OnInit, OnDestroy { ... }
I'm using spectator in my Angular tests and I'm trying to test the component providing the service in the following way:
const createComponent = createComponentFactory({
component: MyComponent,
providers: [
// ... other services ...
mockProvider(MyService),
],
// ...
});
// ...
const spectator = createComponent();
const myService = spectator.inject(MyService);
But whenever I try to mock stuff on myService it does not work: it seems that it is getting a global instance of MyService instead of the component-level instance of MyService.
There are two important steps to take when dealing with component-level provided services in testing.
1) Provide them at component-level in the test
Replace:
With:
Note that the provider is no longer specified in the
createComponentFactorybut increateComponentinstead.2) Get them from the component injector instead of the global one
The
spectator.inject()method takes an optional second parameter calledfromComponentInjector(that isboolean).Replace:
With: