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

181
Vistas
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 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