I hit a wall trying to mock fetch() with jest.
I've tried 2 approaches:
Approach 1: doing it manually as follows:
const pokemon = {
id: 1,
name: 'fake1',
sprites: {other: {'official-artwork': {front_default: 'picture'}}},
types: ['earth']
}
const fakePokemons = JSON.stringify([pokemon, pokemon])
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve(fakePokemons),
})
);
fetchData([1, 4, 7]) // this is the actual funciton call
The error I get is:
TypeError: Cannot read property 'other' of undefined
Which relates to sprites.other.etc... property that the function is failing to extract. I don't understand why when it's clearly there.
Approach 2: using jest-fetch-mock
code:
fetch.mockResponseOnce(JSON.stringify(fakePokemons));
fetchData([1, 4, 7])
In this case I'm stuck with:
FetchError: invalid json response body at reason: Unexpected end of JSON input
I tried with and without JSON.stringify() - no luck. I'm following this tutorial and there both approaches seem to be working
What am I missing?