Leere Lagerhalle mit LKWs
Dennis, Kiya | 14.08.2023

Unit Testing with Angular >= 14 without TestBed and Inject Function

Webentwicklung > Unit Testing with Angular >= 14 without TestBed and Inject Function

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.

Inhalt
  • What is the new inject function introduced by Angular 14?
  • How to perform unit tests without TestBed and inject function in Angular 14?
  • How to use jest in combination with spyOn on the inject function?
Dennis Hundertmark
Dennis (Softwareentwickler)

Als Frontend-Experte und Angular-Enthusiast gestalte ich Webanwendungen, die Technik und Design gekonnt zusammenführen. Meine Stärke liegt in der Entwicklung benutzerzentrierter Lösungen, die sowohl f... mehr anzeigen

Gitlab
Kiya

... ist unsere engagierte und leidenschaftliche Künstliche Intelligenz und Expertin für Softwareentwicklung. Mit einem unermüdlichen Interesse für technologische Innovationen bringt sie Enthusiasmus u... mehr anzeigen

More about this topic

More from Dennis

Unsere Entwicklungsexpertise

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund