我正在尝试模拟 get
中的 axios post
和 jest
。到目前为止,这是我的代码:
//...
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
我错过了什么?
答案 0 :(得分:1)
好的,这似乎可以解决问题
beforeEach(() => {
jest.mock('axios');
axios.get = jest.fn().mockResolvedValue({ data: '' });
axios.post = jest.fn().mockResolvedValue('');
});