NestJS Mock构造函数调用HashiCorpVault



我添加了一个到Hashicorp vault的连接(在映射器服务中(,以获得用于加密的密钥。我需要在服务的构造函数中获取密钥。我的测试现在失败了,因为当映射器服务被实例化时,构造函数被调用,而vault不可用。如果我模拟整个服务,那么我的所有其他测试都将不起作用。所以我只需要模拟构造函数调用,这样它就不会在每次测试之前启动。

mapper.service.ts

@Injectable()
export class Mapper {
key;
encryptionKey;
constructor(private vault: VaultService) {
this.setKey(); // I do not want this to happen in my tests
}
async setKey() {
this.vault.getValueFromVault('soapCredentials', 'encryptionKey').then(async (response) => { 
this.encryptionKey = response;
console.log('this.encryptionKey', this.encryptionKey)
try {
this.key = (await promisify(scrypt)(this.encryptionKey, 'salt', 32)) as Buffer;
} catch {
throw new Error('Encryption set error')
} 
}).catch( err => {
throw new Error(err);
});   
}

mapper.service.spec.ts

describe('Mapper', () => {
let mapper: EnrichementMapper;
let vault: VaultService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
EnrichementMapper,
VaultService
],
}).compile();
mapper = module.get<EnrichementMapper>(EnrichementMapper);
vault = module.get<VaultService>(VaultService);
});
it('should be defined', () => {
expect(mapper).toBeDefined();
});
.... 20 more tests

甚至"应该定义"测试也失败了,因为构造函数正在被调用,而this.setKey((正在被调用。当它试图运行this.vault.getValueFromVault时,会导致错误。我如何模拟构造函数,使其不会激发?

你走在了正确的轨道上。您要做的是确保您的Vault是一个注入的服务,就像您在构造函数中所做的那样。通过这种方式,您可以提供一个mock来替换它

我找到的最简单的方法是,只在mock中定义我需要的函数,以便它们返回集合数据,然后继续测试。

beforeEach()中,将vault服务替换为伪服务的Jest定义。

describe('Mapper', () => {
let mapper: EnrichementMapper;
let vault: VaultService;
beforeEach(async () => {
const FakeVaultService = {
provide: VaultService,
useFactory: () => ({
setKey: jest.fn().mockResolvedValue('Key/Token, whatever'),
}),
};
const module: TestingModule = await Test.createTestingModule({
providers: [
EnrichementMapper,
FakeVaultService
],
}).compile();
mapper = module.get<EnrichementMapper>(EnrichementMapper);
vault = module.get<VaultService>(VaultService);
});
it('should be defined', () => {
expect(mapper).toBeDefined();
});

.... 20 more tests
});

FakeFaultService代码是当您的代码调用setKey时所调用的代码。mockResolvedValue使其异步,因此您也可以进行正确的代码处理。Jest Mock参考

最新更新