尝试在Jest规范中模拟异步获取函数时出错

时间:2017-05-04 12:43:10

标签: javascript testing mocking jestjs

我正在为我的应用编写测试但在尝试模拟异步获取功能时遇到问题。无论我尝试什么,我都会得到:

asyncFetch.mockReturnValue is not a function

这让我相信这个功能并没有被嘲笑。但是,我不知道问题出在哪里。

这是测试:



import emailSignin from 'api/emailSignin';

jest.mock('api/helpers/asyncFetch');

describe('API Auth', () => {
  describe('login', () => {
    it('has a happy path', async () => {
      const asyncFetch = require('api/helpers/asyncFetch').default;

      asyncFetch.mockReturnValue({
        json: () => 'it worked',
      });

      const response = await emailSignin('bob', 'password');
      expect(response).toEqual('it worked');
    });
  });
});




这是我试图嘲笑的模块:



import {
  ClientError,
  ServerError,
  ValidationError,
} from 'api/helpers/errors';

async function asyncFetch(url, requestConfig = {}) {
  const response = await fetch(url, requestConfig);
  const responseBody = await response.json();
  const { statusText, status } = response;

  switch (status) {
    case 400:
    case 401:
    case 403:
      throw new ClientError(statusText, status);
    case 422:
      throw new ValidationError(statusText, status, responseBody.errors);
    case 500:
    case 501:
    case 502:
    case 503:
    case 504:
    case 505:
      throw new ServerError(statusText, status);
    default:
      return response;
  }
}

export default asyncFetch;




非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

要在jest中模拟一个模块,你可以在最初的mock调用中这样做:

jest.mock('api/helpers/asyncFetch', ()=>({
  json: () => 'it worked'
}))