angulartypescriptunit-testingangular-testtestbed

Angular Unit Test - How to inject dependencies to TestBed by using useValue in the TestBed provider


The service I want to test has the following constructor:

constructor(@Inject('enviroment') environment) {
    this.initConfig(environment);
}

The environment is provided in app.module under providers by:

{ provide: 'environment', useValue: environment }

So I configured the TestBed as follows:

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [{ provide: 'environment', useValue: testEnv }, TestService]
    });
    service = TestBed.get(TestService);
});

And I keep getting:

Error: StaticInjectorError(DynamicTestModule)[enviroment]: StaticInjectorError(Platform: core)[enviroment]: NullInjectorError: No provider for enviroment!

The code itself works fine when serving/building so I assume the mistake is somewhere on how I configured the TestBed? I've also tried useFactory to no avail.

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [{ provide: 'environment', useFactory: ()=>testEnv }, TestService]
    });
    service = TestBed.get(TestService);
});

Solution

  • I think it is just a typo.

    It was missing the n in environment

    constructor(@Inject('enviroment') environment) {