Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
Using jest-fetch-mock and receiving null

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

So it looks like my mock request was being reset. In my package.json I had to insert this

  "jest": {
    "resetMocks": false
  },

Apparently CRA updated the default from false to true. similar question / answer here

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!