Suggested way for docs to show mocking axios?
afontcu opened this issue · comments
Hi! 👋 I was writing docs for Making HTTP Requests, and I had this doubt.
There are several ways of mocking a module in Jest, and I'm not sure which one is the one we should showcase in docs:
jest.mock('axios')
axios.get = jest.fn().mockResolvedValue(posts)
jest.mock('axios', () => ({
get: jest.fn(() => posts)
}))
jest.mock('axios')
axios.get.mockResolvedValue(fakePostList)
any preference? any downsides?
disclaimer: docs will mention alternatives such as axios-mock-adapter
or msw
, but I want to keep it simple for the example.
I always use the second one. I find it more flexible for this reason: not sure if this is good practice or not but I often have components making multiple API calls, and I test them like this:
import { mockPosts } from './posts'
import { mockUsers } from './users'
jest.mock('axios', () => ({
get: (url) => {
if (url === '/posts') {
return { data: mockPosts }
}
if (url === '/users') {
return { data: mockUsers }
}
}
}))
I guess mockResolvedValue
is probably the "correct" way to do this, it feels more "jest-y", but I don't know how you handle multiple urls in that case 🤔
All-in-all I don't have a strong opinion on this 👍 all of those seem fine to me,
I ended up using the second one in #26 :)