【问题标题】:how to test history.push with RTL asynchronously in React如何在 React 中使用 RTL 异步测试 history.push
【发布时间】: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


【解决方案1】:
  1. createAuthor 中发生的异步事情是否正确模拟了?那么您的代码是否曾经到达测试中的history.push 行?

  2. 您可以使用waitFor(来自 react-testing-library)来等待测试中的异步事物。所以例如 await waitFor(() =&gt; expect(history.length).toBe(2))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 2021-06-08
    • 2019-08-21
    • 1970-01-01
    • 2020-02-12
    相关资源
    最近更新 更多