From 329b9a24f3e92f4bb04cb46458c04d05bcb37909 Mon Sep 17 00:00:00 2001 From: ersimont <8042088+ersimont@users.noreply.github.com> Date: Mon, 20 Mar 2023 22:00:20 -0400 Subject: [PATCH] feat(ng-dev): support Angular's new `inject()` for test code that executes during a `.run()` callback --- .../src/lib/angular-context/angular-context.spec.ts | 8 ++++++++ .../ng-dev/src/lib/angular-context/angular-context.ts | 7 +++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/projects/ng-dev/src/lib/angular-context/angular-context.spec.ts b/projects/ng-dev/src/lib/angular-context/angular-context.spec.ts index 9b18113f..f403f8cd 100644 --- a/projects/ng-dev/src/lib/angular-context/angular-context.spec.ts +++ b/projects/ng-dev/src/lib/angular-context/angular-context.spec.ts @@ -7,6 +7,7 @@ import { ComponentFactoryResolver, DoCheck, ErrorHandler, + inject, Injectable, InjectionToken, Injector, @@ -129,6 +130,13 @@ describe('AngularContext', () => { expect(completed).toBeTrue(); }); + it('sets an injector context', () => { + const token = new InjectionToken('', { factory: (): string => 'value' }); + new AngularContext().run(() => { + expect(inject(token)).toBe('value'); + }); + }); + it('does not swallow errors (production bug)', () => { expect(() => { new AngularContext().run(() => { diff --git a/projects/ng-dev/src/lib/angular-context/angular-context.ts b/projects/ng-dev/src/lib/angular-context/angular-context.ts index 3df1455c..48faebf1 100644 --- a/projects/ng-dev/src/lib/angular-context/angular-context.ts +++ b/projects/ng-dev/src/lib/angular-context/angular-context.ts @@ -6,6 +6,7 @@ import { import { AbstractType, ApplicationRef, + EnvironmentInjector, InjectionToken, Type, } from '@angular/core'; @@ -158,7 +159,9 @@ export class AngularContext { } /** - * Gets a service or other injectable from the root injector. This implementation is a simple pass-through to [TestBed.inject()]{@linkcode https://angular.io/api/core/testing/TestBed#inject}, but subclasses may provide their own implementation. It is recommended to use this in your tests instead of using `TestBed` directly. + * Gets a service or other injectable from the root injector. Note that you can use Angular's [inject()]{@linkcode https://angular.io/api/core/inject} instead, for code that runs within the {@link .run()} callback. + * + * This implementation is a simple pass-through to [TestBed.inject()]{@linkcode https://angular.io/api/core/testing/TestBed#inject}, but subclasses may provide their own implementation. It is recommended to use this in your tests instead of using `TestBed` directly. */ inject(token: AbstractType | InjectionToken | Type): T { return TestBed.inject(token); @@ -230,7 +233,7 @@ export class AngularContext { jasmine.clock().install(); fakeAsync(() => { jasmine.clock().mockDate(this.startTime); - test(); + this.inject(EnvironmentInjector).runInContext(test); })(); jasmine.clock().uninstall();