嘲笑 axios get 和 post 开玩笑

时间:2021-03-15 14:50:32

标签: javascript jestjs axios

我正在尝试模拟 get 中的 axios postjest。到目前为止,这是我的代码:

//...
jest.mock('axios');
axios.get.mockResolvedValue({ data: '' });
axios.post.mockResolvedValue(null);

test('should match snapshot', () => {
  const { asFragment } = renderComponent();
  expect(asFragment()).toMatchSnapshot();
});
//...

据我所知,它与文档中的完全相同here

具体示例:

// users.test.js
import axios from 'axios';
import Users from './users';

jest.mock('axios');

test('should fetch users', () => {
  const users = [{name: 'Bob'}];
  const resp = {data: users};
  axios.get.mockResolvedValue(resp);

  // or you could use the following depending on your use case:
  // axios.get.mockImplementation(() => Promise.resolve(resp))

  return Users.all().then(data => expect(data).toEqual(users));
});

我得到了 TypeError: _axios.axios.get.mockResolvedValue is not a function

我错过了什么?

1 个答案:

答案 0 :(得分:1)

好的,这似乎可以解决问题

beforeEach(() => {
  jest.mock('axios');
  axios.get = jest.fn().mockResolvedValue({ data: '' });
  axios.post = jest.fn().mockResolvedValue('');
});
相关问题