I'm not sure why I'm receiving null when I'm trying to 'mock' the fetch. I'm using React, along the the punkapi. I'm making a mock request using 'jest-fetch-mock'
fetch.mockResponseOnce(JSON.stringify([{ test: "data" }]))
This is my fake response. I just can't understand why I'm receiving null. The data I receive back is an object within an array, which is working.
This is my fetch request (working):
const random = async () => {
try {
const res = await fetch("https://api.punkapi.com/v2/beers/random");
const newData = await res.json();
return newData
} catch (e) {
return null
}
};
export { random }
This is my test file:
import { random } from "./random";
import fetch from 'jest-fetch-mock'
test("collects data", async () => {
fetch.mockResponseOnce(JSON.stringify([{ test: "data" }]))
const data = await random()
expect(data).toEqual([{
test: "data"
}])
})
I've also update my setupTest.js by adding this.
import fetchMock from 'jest-fetch-mock'
fetchMock.enableMocks()
update
it looks like it was returning NULL from my try catch, but my test still fails.
Cannot read property 'json' of undefined
is my error which is coming from my random async function