Reputation: 5059
I'm trying to mock axios get
and post
in jest
. So far this is my code:
//...
jest.mock('axios');
axios.get.mockResolvedValue({ data: '' });
axios.post.mockResolvedValue(null);
test('should match snapshot', () => {
const { asFragment } = renderComponent();
expect(asFragment()).toMatchSnapshot();
});
//...
As far as I see, it's exactly the same as in the docs here
Exact example:
// 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));
});
And I'm getting TypeError: _axios.axios.get.mockResolvedValue is not a function
What am I missing?
Upvotes: 2
Views: 3741
Reputation: 5059
Ok, this seems to do the trick
beforeEach(() => {
jest.mock('axios');
axios.get = jest.fn().mockResolvedValue({ data: '' });
axios.post = jest.fn().mockResolvedValue('');
});
Upvotes: 5