本文介绍了如何通过传入带有自定义值的ConfigService来测试nestjs服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

launchdarkly.module.ts

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

(此服务/模块让应用程序使用LaunchDarkly功能标记)

如果您愿意,我很乐意展示服务实现,但为简短起见,我跳过了这个问题。重要的是,该服务导入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();
  });
})

我愿意接受任何非粗俗的建议,我只想对我的申请进行功能标记!

推荐答案

假设LaunchdarklyService需要ConfigService,并且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();
  });
})

这篇关于如何通过传入带有自定义值的ConfigService来测试nestjs服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-19 07:45