angularjestjsangular-libraryjest-preset-angulartype-only-import-export

Can't run unit tests when using type-only imports


Follow up on this solution

I've build a library with a component and a directive, which normally causes an import cycle.

Component

import { Component } from '@angular/core';

@Component({
  selector: 'lib-resizable',
  templateUrl: `<div [resizableGlyph]="['top', 'start']"></div>`,
  providers: [
    { provide: 'RESIZABLE', useExisting: ResizableComponent }
  ]
})
export class ResizableComponent {}

Directive

import { Directive, Inject, Input } from '@angular/core';
// import { ResizableComponent } from '../resizable/resizable.component'; // Project won't build (npm run build -- --configuration production)
import type { ResizableComponent } from '../resizable/resizable.component'; // Unit tests don't work
export type Position = 'top' | 'end' | 'bottom' | 'start';

@Directive({ selector: '[resizableGlyph]' })
export class ResizableGlyphDirective {
  constructor(@Inject('RESIZABLE') private resizable: ResizableComponent) { }
  @Input('resizableGlyph') positions: Position[] = [];
}

To solve this we need to use the import type annotation. However this breaks the unit tests (jest):

ReferenceError: ResizableComponent is not defined

I've already checked and tried all comments in the following links:

Here's a minimal reproduction. Did anyone manage to use type-only imports and get the unit-tests to work?

References:


Solution

  • Apparently this is caused when using typed DI in the constructor:

    import type { BsResizableComponent } from '../resizable/resizable.component';
    
    ...
    
    constructor(@Inject(RESIZABLE) private resizable: BsResizableComponent) {
    }
    

    becomes

    import type { BsResizableComponent } from '../resizable/resizable.component';
    
    ...
    
    // Can't use typed DI because of the `import type`
    private readonly resizable: BsResizableComponent;
    constructor(@Inject(RESIZABLE) resizable: any) {
      this.resizable = resizable;
    }
    

    And the problem is solved