Skip to content

Commit

Permalink
feat(ng-dev): support Angular's new inject() for test code that exe…
Browse files Browse the repository at this point in the history
…cutes during a `.run()` callback
  • Loading branch information
ersimont committed Mar 21, 2023
1 parent e2b7f21 commit 329b9a2
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
ComponentFactoryResolver,
DoCheck,
ErrorHandler,
inject,
Injectable,
InjectionToken,
Injector,
Expand Down Expand Up @@ -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(() => {
Expand Down
7 changes: 5 additions & 2 deletions projects/ng-dev/src/lib/angular-context/angular-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import {
AbstractType,
ApplicationRef,
EnvironmentInjector,
InjectionToken,
Type,
} from '@angular/core';
Expand Down Expand Up @@ -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<T>(token: AbstractType<T> | InjectionToken<T> | Type<T>): T {
return TestBed.inject(token);
Expand Down Expand Up @@ -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();

Expand Down

0 comments on commit 329b9a2

Please sign in to comment.