如何在React中用RTL异步测试history.push



所以,我遇到了一个问题。我尝试测试功能:单击按钮调用async。函数,并在最后重定向到新页面。如果调用的函数是同步的,那么下面的测试是有效的,但在异步的情况下,我看不到预期的更改。那么,我做错了什么?

以下是功能:

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;

我的测试:

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);
});
  1. createAuthor中发生的异步事件被正确地模拟了吗?那么,您的代码在测试中是否达到了history.push行?

  2. 您可以使用waitFor(来自react测试库(来等待测试中的异步事件。例如await waitFor(() => expect(history.length).toBe(2))

最新更新