I am testing a component that uses a useEffect
hook that fetches data from an API, updates state and then builds out the component. I've mocked the API response successfully for several tests using
If I reject the promise, I still get the same error but get the thrown exception with it too:
global.fetch = jest.fn().mockImplementationOnce(() => {
Promise.reject({
status: 400,
json: () => Promise.resolve({ success: false, error: 'Something bad happened' }),
})
})
The API uses a NextApiResponse and looks like this:
try {
// Query data from database
const data = methodThatGetsDataFromDatabase()
return res.status(200).json({ success: true, data: data })
} catch (error) {
return res.status(400).json({ success: false, error: error.message })
}
I've been working at this for a long time and have about worn Google out looking for answers. I just can't figure out why fetch
is undefined rather than returning the promise. Any help is greatly appreciated!
CodePudding user response:
The difference I found is that, your successful fetch mock actually returns the Promise.
But the failing fetch mock is not returning -- notice the subtle addition of curly braces around that Promise. Can you check this without that curly brackets?
global.fetch = jest.fn().mockImplementationOnce(() =>
Promise.resolve({
status: 400,
json: () => Promise.resolve({ success: false, error: 'Something bad happened' }),
})
)