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

152
Visualizações
how to test history.push with RTL asynchronously in React

So, I was faced with a problem. I tried to test functionality: Click on a button to invoke async. function and on the end redirect to a new page. The test below works if the invoked function is synchronous but in asynchronous case, I don't see expected changes. So, what I'm doing wrong?

Here is the function:

import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';

import { ROUTE_AUTHOR_LIST } from '../../constants';
import { createAuthor } from '../../services/authors';


const AuthorCreate = () => {
    const history = useHistory();

    const handleSave = async () => {
        const payload = ...
        await createAuthor(payload);
        history.push(ROUTE_AUTHOR_LIST);
    };


    return (
    <div>
        <Button variant="primary" onClick={ handleSave }>
          Save
        </Button>
    </div>
    );
}

export default AuthorCreate;

My test:

import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { createMemoryHistory } from "history";
import { Router } from "react-router-dom";
import { ROUTE_AUTHOR_LIST } from "../constants";

describe("Save button functionality", () => {
  test("redirect to correct URL", async () => {
    const history = createMemoryHistory();
    render(
      <Router history={history}>
        <AuthorCreate />
      </Router>
    );
    expect(
      screen.getByRole("heading", { name: /create author/i })
    ).toBeInTheDocument();

    const saveBtn = screen.getByRole("button", {
      name: /save/i,
      type: "button",
    });

    userEvent.click(saveBtn);

   // NOT PROPERLY WORKS
    expect(await history.length).toBe(2); 
    expect(await history.location.pathname).toBe(ROUTE_AUTHOR_LIST);
  });
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. Is the asynchronous thing happening in createAuthor mocked correctly? So is your code ever reaching the history.push line in the test?

  2. You can use waitFor (from react-testing-library) to wait for asynchronous things in test. So for example await waitFor(() => expect(history.length).toBe(2))

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