Jest Mock Promise with Params

自作多情 提交于 2020-01-06 07:14:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!