mercredi 30 octobre 2019

Angular Testing: How to provide Injector?

I try to build an Angular component which depends on an Injector providing an InjectorToken:

import { Component, Injector, InjectionToken } from '@angular/core';

const TOKEN = new InjectionToken<string>('token');

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent {
  constructor(injector: Injector) {
    injector.get(TOKEN);
  }
}

However, I can not get the test running for this component and get following error:

NullInjectorError: StaticInjectorError(DynamicTestModule)[InjectionToken token]: 
  StaticInjectorError(Platform: core)[InjectionToken token]: 
    NullInjectorError: No provider for InjectionToken token!

The following approach to provide the Injector in the TestBed didn't work:

TestBed.configureTestingModule({
  declarations: [ TestComponent ],
  providers: [
    { provide: Injector, useValue: Injector.create({providers: [
      {
        provide: new InjectionToken<string>('token'),
        useValue: '',
        deps: []
      }
    ]}) }
  ]
})

How can I setup the test environment correctly?

Aucun commentaire:

Enregistrer un commentaire