NestJS E2E Tests: ConfigService is undefined when injected into providers

1 day ago 4
ARTICLE AD BOX

I'm having issues with dependency injection in my NestJS E2E tests using Vitest. The ConfigService works perfectly when running the application locally, but it's undefined when providers try to use it during tests.

Error:

TypeError: Cannot read properties of undefined (reading 'get') at new GoogleStrategy (google.strategy.ts:11:31)

Code:

@Injectable() export class GoogleStrategy extends PassportStrategy(Strategy, 'google') { constructor(configService: ConfigService<EnvironmentVariables>) { super({ clientID: configService.get('GOOGLE_CLIENT_ID'), clientSecret: configService.get('GOOGLE_CLIENT_SECRET'), callbackURL: configService.get('GOOGLE_CALLBACK_URL'), scope: ['email', 'profile'], }); } }

Error:

TypeError: Cannot read properties of undefined (reading 'get') at AuthController.getGoogleURL (/home/vitor/workspace/scalable-e-commerce-server/services/auth/src/modules/auth/infrastructure/adaptars/primary/http/auth.controller.ts:58:44)

Code:

@Get('google') getGoogleURL() { const redirectUri = this.configService.get('GOOGLE_CALLBACK_URL'); const clientID = this.configService.get('GOOGLE_CLIENT_ID'); }

Test Setup:

describe('AuthController (E2E)', () => { let app: INestApplication; beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleFixture.createNestApplication<NestFastifyApplication>( new FastifyAdapter(), ); await app.init(); await app.getHttpAdapter().getInstance().ready(); }); afterAll(async () => { await app.close(); }); it('should be defined', () => { expect(app).toBeDefined(); }); });

AppModule Configuration:

@Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, envFilePath: [getCurrentNodeENV()], validate: validateENV, }), AuthModule, ], controllers: [], }) export class AppModule {}

AuthModule Configuration

@Module({ imports: [], controllers: [AuthController], providers: [ GoogleStrategy, // ... other providers ], }) export class AuthModule {}

getCurrentNodeENV return env file path ( yes, the file path is correct)

What I've Tried (that didn't work)

Using .overrideProvider(ConfigService).useValue(mockConfigService)

Setting environment variables directly with process.env.GOOGLE_CLIENT_ID = 'value'

Creating a separate test configuration module

Question

Why is ConfigService undefined when injected into providers during E2E tests, even though:

The ConfigModule is configured as isGlobal: true

Environment variables are loaded correctly

Validation passes

The same setup works in the actual application?

How can I make ConfigService available to all providers during E2E tests?

Read Entire Article