Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

200
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda