【发布时间】:2021-11-28 12:06:17
【问题描述】:
所以,我遇到了一个问题。 我试图测试功能: 单击一个按钮以调用异步。功能并最终重定向到新页面。 如果调用的函数是同步的,则下面的测试有效,但在异步情况下,我看不到预期的变化。 那么,我做错了什么?
函数如下:
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);
});
【问题讨论】:
-
不要将 RTL 用于 react-testing-library,因为该快捷方式意味着 Right To Left in HTML 在某些语言中从右侧显示文本的方式。这很令人困惑。我建议将问题重命名为“如何在反应测试库中异步测试历史记录。推送”因为现在这个问题没有意义。
-
试试
(await history).length?
标签: javascript reactjs jestjs react-testing-library