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

186
Visualizações
setState not working in Jest test using React Testing Library

On a given component, I'm mocking an API call which returns some markup for an HTML document. I managed to get the mock working and the mock response is being returned, but my component is not able to set the state with this response. Here's how it looks like.

export const RetrieveContent = (props: Props) => {
  const [content, setContent] = useState < Partial < ContentViewModel >> {};
  useEffect(() => {
    const requestContent = async (props: Props) => {
      const { id } = props;
      const data = await getContent(id);
      // console.log(data) <-- This logs the object correctly!
      setContent(data);
    };
    requestContent(props);
  }, []);
  return <>{parse(content.contentObject.content.body)}</>; // content is an empty object here
};

After calling setState, the state is still an empty object. The test is rather simple.

cconst server = setupServer(
  rest.get('/content/*', (req, res, ctx) => {
    return res(ctx.json(ContentViewModelMock))
  })
)

describe('<Content /> tests', () => {

  beforeAll(() => server.listen())
  beforeEach(() => server.resetHandlers())
  afterAll(() => server.close())

  test('should display content when the id is found', async () => {
    const { asFragment } = render(<Content id={`${faker.datatype.uuid}`} />)
    console.log(asFragment().textContent) // This returns nothing
  })
})

about 4 years ago · Santiago Gelvez
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