Skip to content

Commit 168b1f3

Browse files
authored
docs(oninit-lifecycle-tests): mocked services in OnInit (#456)
1 parent 1dffa19 commit 168b1f3

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ Spectator helps you get rid of all the boilerplate grunt work, leaving you with
6060
- [Testing Pipes](#testing-pipes)
6161
- [Using Custom Host Component](#using-custom-host-component)
6262
- [Mocking Providers](#mocking-providers)
63+
- [Mocking OnInit Dependencies](#mocking-oninit-dependencies)
6364
- [Jest Support](#jest-support)
6465
- [Testing with HTTP](#testing-with-http)
6566
- [Global Injections](#global-injections)
@@ -905,6 +906,28 @@ const createService = createServiceFactory({
905906
});
906907
```
907908
909+
### Mocking OnInit dependencies
910+
911+
If a component relies on a service being mocked in the [OnInit](https://angular.io/api/core/OnInit) lifecycle method, change-detection needs to be disabled until after the services have been injected.
912+
913+
To configure this, change the `createComponent` method to have the `detectChanges` option set to false and then manually call `detectChanges` on the spectator after setting up the injected services.
914+
915+
```ts
916+
const createComponent = createComponentFactory({
917+
component: WeatherDashboardComponent
918+
});
919+
920+
it('should call the weather api on init', () => {
921+
const spectator = createComponent({
922+
detectChanges: false
923+
});
924+
const weatherService = spectator.inject(WeatherDataApi);
925+
weatherService.getWeatherData.andReturn(of(mockWeatherData));
926+
spectator.detectChanges();
927+
expect(weatherService.getWeatherData).toHaveBeenCalled();
928+
})
929+
```
930+
908931
## Jest Support
909932
By default, Spectator uses Jasmine for creating spies. If you are using Jest as test framework instead, you can let Spectator create Jest-compatible spies.
910933

0 commit comments

Comments
 (0)