这是我试图用 Jest 编写单元测试的方法
async function getParameter(parameter: string,
withDecryption: boolean = false): Promise<String> {
const params = {
Name: parameter,
WithDecryption: withDecryption,
};
try {
const request = await ssmClient.getParameter(params).promise();
return request.Parameter.Value;
} catch (err) {
logger.error(`Error ${err}`);
throw Error(err);
}
}
测试方法 :
test('getParameterFromSystemManager', async () => {
const mockedResponseData = {
Parameter: {
Value: 'parameterValue',
},
};
ssmClient.getParameter(params).promise = jest.fn();
ssmClient.getParameter(params).promise.mockImplementation(() => Promise.resolve(mockedResponseData));
const data =
await SSMParameters.getParameterFromSystemManager('testurl', false,
'Test', 'elastic');
expect(data).toEqual(mockedResponseData.Parameter.Value);
expect(ssmClient.getParameter).toHaveBeenCalledTimes(1);
});
我得到错误:
TypeError: ssmClient.getParameter(...).promise.mockImplementation 不是函数
我们如何在 Jest 中模拟这样的 .promise() 函数?