在 Nest.js 中运行测试用例时,ConfigService 未定义

问题描述 投票:0回答:2

我在本地运行 Nestjs 服务器,如果我用邮递员测试它工作正常。但是当我运行测试用例时,ConfigService 未定义!

app.module.ts

@Module({
  imports: [
    ConfigModule.forRoot({ load: [configuration], isGlobal: true }),
    AppDeployModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

配置.ts

export default () => ({
  app: {
    baseUrl: 'https://app-deploy.com',
  },
});

应用程序部署.controller.spec.ts

describe('AppDeployController', () => {
  let controller: AppDeployController;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [AppDeployController],
      providers: [AppDeployService],
      imports: [ConfigModule],
    }).compile();

    controller = module.get<AppDeployController>(AppDeployController);
  });

  it.only('should create an app', async () => {
    const res = await controller.create({ appName: 'Hello World' });
    console.log(res);
  });
});
在服务文件中,configService.get('app') 未定义!

应用程序部署.service.ts

@Injectable()
export class AppDeployService {
  constructor(private configService: ConfigService) {}

  create(createAppDeployDto: CreateAppDeployDto) {
    console.log(this.configService.get('app')); // Here while running test it gets undefined

    const baseUrl = this.configService.get('app').baseUrl;

    return {
      appName: createAppDeployDto.appName,
      appUrl:
        baseUrl +
        '/' +
        createAppDeployDto.appName.toLowerCase().replace(' ', '-'),
    };
  }
}

这是运行测试后的结果。

FAIL  src/app-deploy/app-deploy.controller.spec.ts
  AppDeployController
    × should create an app (51 ms)

  ● AppDeployController › should create an app

    TypeError: Cannot read properties of undefined (reading 'baseUrl')

      11 |     console.log(this.configService.get('app')); // Here while running test it gets undefined
      12 |
    > 13 |     const baseUrl = this.configService.get('app').baseUrl;
         |                                                  ^
      14 |
      15 |     return {
      16 |       appName: createAppDeployDto.appName,

      at AppDeployService.create (app-deploy/app-deploy.service.ts:13:50)
      at AppDeployController.create (app-deploy/app-deploy.controller.ts:12:34)
      at Object.<anonymous> (app-deploy/app-deploy.controller.spec.ts:20:34)
jestjs nestjs nestjs-config nestjs-testing
2个回答
1
投票

在您的

app-deploy.controller.spec.ts
中,尝试更改这部分代码:

const module: TestingModule = await Test.createTestingModule({
  controllers: [AppDeployController],
  providers: [AppDeployService],
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
    }),
  ],
}).compile();

controller = module.get<AppDeployController>(AppDeployController);

0
投票

有 2 种方法可以解决此问题:

  1. 当您创建测试模块时,“导入”配置模块,就像在应用程序根模块中导入它一样: 例如:
const module = await Test.createTestingModule({
  imports: [
    CacheModule.register({ isGlobal: true, ttl: 60000 }),
    ConfigModule.forRoot({
      load: Configs, // imported from another file
      ignoreEnvFile: false,
      isGlobal: true,
      cache: true,
      envFilePath: [".env"],
    }),
  ],
  providers: [ConfigService],
})
  .overrideProvider(PinoLogger)
  .useValue({
    info: jest.fn(() => Promise.resolve(null)),
  })
  .compile();

  1. 如果您没有大量的 ENV 变量,请模拟配置服务
const module = await Test.createTestingModule({
  imports: [CacheModule.register({ isGlobal: true, ttl: 60000 })],
  providers: [
    {
      provide: configService,
      useValue: {
        get: jest.fn(() =>
          Promise.resolve({
            VARIABLE_NAME: VALUE,
          })
        ),
      },
    },
  ],
})
  .overrideProvider(PinoLogger)
  .useValue({
    info: jest.fn(() => Promise.resolve(null)),
  })
  .compile();
© www.soinside.com 2019 - 2024. All rights reserved.