0

In the Nx workspace we are working on, we are sharing the app environment variables with other Nx libs via InjectionToken via the AppModule.

In the app.module.ts:

import { environment } from '../environments/environment';

@NgModule({
   providers: [
      {
         provider: 'environment', useValue: environment
      }
   ]
})
export class AppModule {}

Then in any service.ts files in the libs where we want to use the environment variables we would call them like:

import { Environment } from '../models/environment.model';

@Injectable({
  providedIn: 'root'
})
export class BookService {

   readonly apiUrl: string;

   constructor( @Inject('environment') environment: Environment ) { 
      this.apiUrl = environment.apiUrl;
   }
}

In addition, we also need this environment value to be available in the .spec file to run the test suites. Without it the Jest test runner would throw the error NullInjectorError: R3InjectorError(DynamicTestModule)[BookService -> environment -> environment]: NullInjectorError: No provider for environment!

Our roadblock now is we are not sure how to provide this environment value to the .spec files without directly importing it from the apps directory.

We have in fact tried importing it from the apps directory like the following code and it did pass the test suite.

Any advice on how to properly use the InjectionToken in the .spec files?

import { environment } from '../../../../../../apps/my-app/src/environments/environment';

describe('BookService', () => {
   beforeEach(() => {
      TestBed.configureTestingModule({
         imports: [HttpClientTestingModule],
         providers: [
            {
               provide: 'environment', useValue: environment
            }
         ]
      });
   });
});
user2268244
  • 244
  • 1
  • 15

0 Answers0