我创建了一个服务,它的模块如下所示:
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();
});
})我愿意接受任何无伤大雅的建议,我只想把我的应用程序标记出来!
发布于 2021-01-08 22:17:12
假设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();
});
})发布于 2022-05-13 21:51:44
您不需要提供ConfigService,而是需要导入带有模拟数据的ConfigModule。作为一个例子
imports: [CommonModule,ConfigModule.forRoot({
ignoreEnvVars: true,
ignoreEnvFile: true,
load: [() => ({ IntersectionOptions: { number_of_decimal_places: '3' }})],
})],https://stackoverflow.com/questions/65636980
复制相似问题