问题
This is the method I am trying to write Unit test in 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 Method :
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);
});
I get the error :
TypeError: ssmClient.getParameter(...).promise.mockImplementation is not a function
How do we mock such .promise() functions in Jest ?
回答1:
The reason why .promise.mockImplementation
is not a function is that calling getParameter(...)
returns a new instance/object with a new .promise()
.
So in your first line: ssmClient.getParameter(params).promise = jest.fn();
you only set that instance with jest.fn()
.
In the second line you're actually calling .mockImplementation()
on a brand new instance.
Instead you're going to have to mock getParameter()
to make sure it returns your mock everytime.
ssmClient.getParameter = jest.fn();
ssmClient.getParameter.mockImplementation(() => ({
promise: jest.fn().mockImplementation(() => Promise.resolve(mockedResponseData));
}))
来源:https://stackoverflow.com/questions/54406751/jest-mock-promise-with-params