Search code examples
angulartypescriptdependency-injectionjasmineangular-test

Angular Testing provider useValue for environment throws NullInjectionError


I have a provider for environment in our Angular application and we have it like this:

{ provide: 'environment', useValue: environment }

Alongside this we have a lot of other providers as services as well. Now this works fine in the application but when I run ng test it throws an error for any service that uses it.

NullInjectorError: No provider for environment

@Inject('environment') environment: Environment

How do I progress on this since I need the environment to be injected automatically as well.


Solution

    1. Create a new file testing.module.ts in your project:
    import { NgModule } from '@angular/core';
    import { environment } from '../environments/environment';
    
    @NgModule({
      providers: [
        { provide: 'environment', useValue: environment }
      ]
    })
    export class TestingModule { }
    
    1. Import TestingModule in your test files:
    import { TestingModule } from './testing.module';
    
    describe('MyService', () => {
      beforeEach(() => TestBed.configureTestingModule({
        imports: [ TestingModule ],
        // other configuration
      }));
    
      it('should be created', () => {
        const service: MyService = TestBed.get(MyService);
        expect(service).toBeTruthy();
      });
    });