Search code examples
angulartestingdependency-injectionkarma-runnerangular-pipe

How to test a Angular pipe with own dependencies (injected with NG 15 inject())?


A minimum working example, in a fresh Angular 15 CLI app:

  • A (blank) service HelperService
  • This service gets injected into DemoPipe with the new inject() call:
export class DemoPipe implements PipeTransform {
  private readonly helper = inject(HelperService);
  ...
}

The default pipe test created by NG-cli will fail, as the constructor call happens outside the DI context:

it('create an instance', () => {
  const pipe = new DemoPipe();
  expect(pipe).toBeTruthy();
});
Error: NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `EnvironmentInjector#runInContext`. Find more at https://angular.io/errors/NG0203
        error properties: Object({ code: -203 })

Is there any wrapper I could use in Karma to provide the missing environment?


Solution

  • You can try the following:

    describe('DemoPipe', () => {
     let pipe:DemoPipe;
    
      beforeEach(async () => {
        TestBed.configureTestingModule({ providers: [DemoPipe,HelperService] });
      });
    
    it('create an instance', () => {
      pipe = TestBed.inject(DemoPipe);
      expect(pipe).toBeTruthy();
    });
    

    I tried and it works