This article discusses testing Angular code, which uses the inject function for dependency injection.
If you are more of a visual learner, here's a video for you:
Why inject?
The inject function, introduced in Angular 14, is an alternative to the constructor-based dependency injection. inject has the following advantages:
1. Standardization of Decorators
Decorators have existed in an experimental setting within the TypeScript configuration.
While TC39 has completed the standardization of decorators, all decorator types must be finalized to disable the experimental mode of the TypeScript compiler.
Unlike the constructor, the inject function works without parameter decorators, eliminating potential risks for future breaking changes associated with dependency injection via the constructor.
classFlightSearchComponent{constructor(@SkipSelf()// not standardized@Optional()// not standardizedprivateflightService1:FlightService){}privateflightService2=inject(FlightService,{skipSelf:true,optional:true,});}
2. Erased Type in the constructor
The type of inject is also available during runtime. With the constructor, only the variable name survives the compilation. So, the TypeScript compiler has to add specific metadata where type information is part of the bundle. This setting is not the default behavior of the compiler.
// Compiled JavaScriptclassFlightService{}classFlightSearchComponent{// type is goneconstructor(flightService){this.flightService=flightService;// type is still therethis.flightService2=inject(FlightService);}}
3. Class Inheritance
inject is more accessible for class inheritance. With the constructor, a subclass has to provide all dependencies for its parents. With inject, the parent get their dependencies on their own.
// Inheritance and constructor-based dependency injectionclassAnimal{constructor(privateanimalService:AnimalService){}}classMammalextendsAnimal{constructor(privatemammalService:MammalService,animalService:AnimalService){super(animalService);}}classCatextendsMammal{constructor(privatecatService:CatService,mammalService:MammalService,animalService:AnimalService){super(mammalService,animalService);}}
// Inheritance via injectclassAnimal{animalService=inject(AnimalService);}classMammalextendsAnimal{mammalService=inject(MammalService);}classCatextendsMammal{catService=inject(CatService);}
4. Type-Safe Injection Tokens
Injection Tokens are type-safe.
constVERSION=newInjectionToken<number>('current version');classAppComponent{//compiles, although VERSION is of type numberconstructor(@Inject('VERSION')unsafeVersion:string){}safeVersion:string=inject(VERSION);// fails 👍}
5. Functional Approaches
Some functional-based approaches (like the NgRx Store) that don't have a constructor can only work with inject.
Because of these many advantages, inject was the rising star. It almost looked like the constructor-based approach might become deprecated.
At the time of this writing, things shifted a little bit. According to Alex Rickabaugh, property decorators are in Stage 1 regarding standardization. That's why he recommends using whatever fits best and waiting for the results of the TC39.
Many tests face issues when the application code switches to inject. One of the main issues is the instantiation. With a constructor-based class, a test could directly instantiate the class, but with inject, that is impossible, and we always have to go via the TestBed.
Whenever dealing with a Service/@Injectable, we can call TestBed.inject from everywhere in our test.
That could be at the beginning of the test, in the middle, or even at the end.
We have the following Service, which we want to test:
AddressAsyncValidator injects the HttpClient. So we have to mock that one.
There is no need to import or create a component in our TestingModule.
It is pure "logic testing". The test doesn't require a UI, i.e., DOM rendering.
describe("AddressAsyncValidator",()=>{it("should validate an invalid address",waitForAsync(async ()=>{TestBed.configureTestingModule({providers:[{provide:HttpClient,useValue:{get:()=>of([]).pipe(delay(0))},},],});constvalidator=TestBed.inject(AddressAsyncValidator);constisValid=awaitlastValueFrom(validator.validate({value:"Domgasse 5"}asAbstractControl));expect(isValid).toEqual({address:"invalid"});}));});
That test will succeed. There are two remarks, though.
First, if AddressAsyncValidator has no {providedIn: 'root'} (only @Injectable is available), we have to provide the Service in the TestingModule:
@Injectable()exportclassAddressAsyncValidator{// ...}describe("AddressAsyncValidator",()=>{it("should validate an invalid address",waitForAsync(async ()=>{TestBed.configureTestingModule({providers:[AddressAsyncValidator,{provide:HttpClient,useValue:{get:()=>of([]).pipe(delay(0))},},],});// rest of the test}));});
Second, we cannot run inject inside the test. That will fail with the familiar error message.
NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with runInInjectionContext.
describe("AddressAsyncValidator",()=>{it("should validate an invalid address",waitForAsync(async ()=>{TestBed.configureTestingModule({providers:[AddressAsyncValidator,{provide:HttpClient,useValue:{get:()=>of([]).pipe(delay(0))},},],});constvalidator=inject(AddressAsyncValidator);// not good}));});
TestBed.runInInjectionContext
Why would we ever want to run inject in a test? Answer: Whenever we have to test a function which uses inject.
In the Angular framework, that could be an HttpInterceptorFn or one of the router guards, like CanActivateFn.
In the Angular community, we currently see many experiments with functional-based patterns.
Nxtensions is a set of plugins and utilities for Nx.
Nx is a smart and extensible build framework. At its core, it offers many great features like:
Project and task graph creation and analysis.
Orchestration and execution of tasks.
Computation caching.
Code generation.
Its core functionality can be further extended with plugins to support frameworks and technologies not supported by the core plugins maintained by the Nx team.
[x] Tests for the changes have been added (for bug fixes / features)
[ ] Docs have been added / updated (for bug fixes / features)
PR Type
What kind of change does this PR introduce?
[ ] Bugfix
[x] Feature
[ ] Code style update (formatting, local variables)
[ ] Refactoring (no functional changes, no api changes)
[ ] Build related changes
[ ] CI related changes
[ ] Documentation content changes
[ ] Other... Please describe:
Which package are you modifying?
[x] vite-plugin-angular
[ ] vite-plugin-nitro
[ ] astro-angular
[ ] create-analog
[ ] router
[ ] platform
[ ] content
[ ] nx-plugin
[ ] trpc
What is the new behavior?
This PR enables support for .analog file extension via the supportAnalogFormat flag under vite.experimental.
This replaces the .ng file extension support. With .analog, the separation is clearer (and intentional). Level of support is around the same as .ng with the following difference:
templateUrl is now supported for external HTML file
styleUrl and styleUrls are now supported for external style file(s)
<style> (for inline style) is now converted to styles property in the Component metadata instead of prepend in the <template> content
Multiple <style> is not guaranteed. If folks need multiple stylesheet, use styleUrls instead
Does this PR introduce a breaking change?
[ ] Yes
[x] No
Other information
[optional] What gif best describes this PR or how it makes you feel?
apiCheckGuard is a simple function that verifies if a request to the URL "/holiday" succeeds. There is no constructor in a function. Therefore, apiCheckGuard must use inject.
That will also not work. We get the NG0203 error again.
The solution is TestBed.runInInjectionContext. As the name says, it allows us to run any function, which will run again in the injection context. That means the inject is active and will work as expected.
Although it looks like TestBed.runInInjectionContext provides the injection context asynchronously, that is not true.
The guard calls inject synchronously. If it did it in the pipe operator, inject would run in the asynchronous task and again fail.
Summary
inject comes with many advantages over the constructor-based dependency injection, and you should consider using it.
HttpInterceptorFn and router guards are functions and can only use inject to get access to the dependency injection.
To have a working inject, we must wrap those function calls within TestBed.runInInjectionContext.
There is also TestBed.inject, which behaves differently. It is only available in tests and we should use it get instances of classes. Regardless, if those classes use inject or the constructor-based dependency injection.