Since the introduction of Angular 14 by the Angular Team, a new 'inject' function has been implemented. This function enables the use of services or other dependencies in a component without the need of a constructor. However, this requirement leads to the use of the TestBed
in testing the service, which can often be slightly frustrating for efficient unit tests.
However, there is a workaround for this, by importing everything from the @angular/core
, and then the jest
in combination with spyOn
can be used on the inject
function. Subsequently, you can simply verify the providerToken
and provide the corresponding mock or service as a return value. Here's an example:
1// import * as core from '@angular/core';
2...
3jest.spyOn(core, 'inject').mockImplementation((providerToken => {
4 if (providerToken === ApiService) {
5 return mockApiService;
6 }
7}));
8...
If you want more details on this, Rainer Hahnekamp has released a very good video on the topic.