just-jeb / angular-builders

Angular build facade extensions (Jest and custom webpack configuration)
MIT License
1.14k stars 198 forks source link

`import type` statement causes `ReferenceError: ..._2 is not defined` for injected dependency #1772

Open raphaelmeyer opened 5 months ago

raphaelmeyer commented 5 months ago

Describe the Bug

Given a service with a dependency injected though a token and a test for the service, the test fails with a ReferenceError for the injection token depending on the import statement in the service.

For example a service...

@Injectable({ providedIn: 'root' })
export class ExampleService {
  public constructor(
    @Inject(EXAMPLE_TOKEN) private readonly _dependency: ExampleDependency
  ) {}

  public foo(): number {
    return this._dependency.foo();
  }
}

...with a dependency...

export interface ExampleDependency {
  foo: () => number;
}

export const EXAMPLE_TOKEN = new InjectionToken<ExampleDependency>('example.token');

...and a test:

describe('Service', () => {
  const fake: ExampleDependency = {
    foo: () => 42,
  };

  it('should do something', () => {
    TestBed.configureTestingModule({
      providers: [ExampleService, { provide: EXAMPLE_TOKEN, useValue: fake }],
    });

    const service = TestBed.inject(ExampleService);
    expect(service.foo()).toStrictEqual(42);
  });
});

Depending on the import statement for the dependency in the service, the test fails with a ReferenceError: example_dependency_2 is not defined.

The following import causes the error:

import { EXAMPLE_TOKEN } from './example.dependency';
import type { ExampleDependency } from './example.dependency';

But combining them into a single import (even with type) works as expected:

import { EXAMPLE_TOKEN, type ExampleDependency } from './example.dependency';

Minimal Reproduction

https://github.com/raphaelmeyer/angular-builder-jest-import-error

npm install
npx ng test

Expected Behavior

I would expect the same behavior from both import statement variants.

Environment

Angular CLI: 17.3.7
Node: 20.11.1
Package Manager: npm 10.2.4
OS: linux x64

Angular: 17.3.8
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1703.7
@angular-devkit/build-angular   17.3.7
@angular-devkit/core            17.3.7
@angular-devkit/schematics      17.3.7
@angular/cli                    17.3.7
@schematics/angular             17.3.7
rxjs                            7.8.1
typescript                      5.4.5
zone.js                         0.14.5

Additional Context

I just did a quick test with @angular-devkit/build-angular:jest instead of @angular-builders/jest:run. Then the error does not occur.