Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda