【问题标题】:Mocking axios get and post in jest嘲笑 axios get 和 post 开玩笑
【发布时间】:2021-03-15 23:14:38
【问题描述】:

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

//...
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

我错过了什么?

【问题讨论】:

    标签: javascript jestjs axios


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 2019-01-02
      相关资源
      最近更新 更多