Home > Back-end >  Nestjs: cannot inject ConfigService while testing
Nestjs: cannot inject ConfigService while testing

Time:05-04

I'm having problems setting up a unit test that utilizes the ConfigService to set up TypeORM. The test below fails with the following message:

Nest can't resolve dependencies of the TypeOrmModuleOptions (?). Please make sure that the argument ConfigService at index [0] is available in the TypeOrmCoreModule context.

I've tried adding the ConfigService as a provider, but with no luck. Any ideas on what I'm doing wrong?

import { ConfigModule, ConfigService } from '@nestjs/config';
import { Test } from '@nestjs/testing';
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';

describe('TypeORM setup', () => {
    beforeEach(async () => {
        await Test.createTestingModule({
            providers: [ConfigService],
            imports: [
                ConfigModule.forRoot(),
                TypeOrmModule.forRootAsync({
                    useFactory: (config: ConfigService) => ({ ...config.get('db') }),
                    inject: [ConfigService],
                }),
            ],
        }).compile();
    });

    it('dummy', () => {
        true === true;
    });
});

CodePudding user response:

You either need to set { isGlobal: true } as an option for the ConfigModule or you need to add imports: [ConfigModule] to the TypeOrmModule.forRootAsync() configuration

  • Related