Entonces, me enfrenté a un problema. Traté de probar la funcionalidad: haga clic en un botón para invocar asíncrono. función y al final redirigir a una nueva página. La prueba a continuación funciona si la función invocada es sincrónica, pero en el caso asincrónico, no veo los cambios esperados. Entonces, ¿qué estoy haciendo mal?
Aquí está la función:
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;Mi prueba:
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); });¿Se burla correctamente lo asincrónico que sucede en createAuthor? Entonces, ¿alguna vez su código llega a la línea history.push en la prueba?
Puede usar waitFor (de react-testing-library) para esperar cosas asincrónicas en la prueba. Entonces, por ejemplo await waitFor(() => expect(history.length).toBe(2))