如何通过传入具有自定义值的 ConfigService 来测试 nestjs 服务?

How to test a nestjs service by passing in a ConfigService with custom values?

我创建了一个服务,它的模块如下所示:

launchdarkly.module.ts

@Module({
  providers: [LaunchdarklyService],
  exports: [LaunchdarklyService],
  imports: [ConfigService],
})
export class LaunchdarklyModule {}

(这个service/module是为了让应用程序使用LaunchDarkly feature-flagging)

如果您愿意,我很乐意展示服务实现,但为了缩短这个问题,我跳过了它。重要的一点是此服务导入 ConfigService(用于获取 LaunchDarkly SDK 密钥)。

但是如何测试 Launchdarkly 服务?它从 ConfigService 读取一个键,所以我想在 ConfigService 具有各种值的地方编写测试,但经过数小时的尝试我无法弄清楚如何在测试中配置 ConfigService

这是测试:

launchdarkly.service.spec.ts

describe('LaunchdarklyService', () => {
  let service: LaunchdarklyService;

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

    service = module.get<LaunchdarklyService>(LaunchdarklyService);
  });

  it("should not create a client if there's no key", async () => {
    // somehow I need ConfigService to have key FOO=undefined for this test
    expect(service.client).toBeUndefined();
  });

  it("should create a client if an SDK key is specified", async () => {
    // For this test ConfigService needs to specify FOO=123
    expect(service.client).toBeDefined();
  });
})

我愿意接受任何非 hacky 的建议,我只想对我的应用程序进行功能标记!

假设 LaunchdarklyService 需要 ConfigService 并且注入到构造函数中,您可以通过使用 Custom Provider 来提供 ConfigService 的模拟变体返回您需要的自定义凭据。例如,您的测试模拟可能看起来像

describe('LaunchdarklyService', () => {
  let service: LaunchdarklyService;
  let config: ConfigService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [LaunchdarklyService, {
        provide: ConfigService,
        useValue: {
          get: jest.fn((key: string) => {
            // this is being super extra, in the case that you need multiple keys with the `get` method
            if (key === 'FOO') {
              return 123;
            }
            return null;
          })
        }
      ],
    }).compile();

    service = module.get<LaunchdarklyService>(LaunchdarklyService);
    config = module.get<ConfigService>(ConfigService);
  });

  it("should not create a client if there's no key", async () => {
    // somehow I need ConfigService to have key FOO=undefined for this test
    // we can use jest spies to change the return value of a method
    jest.spyOn(config, 'get').mockReturnedValueOnce(undefined);
    expect(service.client).toBeUndefined();
  });

  it("should create a client if an SDK key is specified", async () => {
    // For this test ConfigService needs to specify FOO=123
    // the pre-configured mock takes care of this case
    expect(service.client).toBeDefined();
  });
})

您需要导入带有模拟数据的 ConfigModule,而不是提供 ConfigService。 举个例子

imports: [CommonModule,ConfigModule.forRoot({
                ignoreEnvVars: true,
                ignoreEnvFile: true,
                load: [() => ({ IntersectionOptions: { number_of_decimal_places: '3' }})],
            })],