【问题标题】:Testing the return value from an useMemo with React/Jest使用 React/Jest 测试 useMemo 的返回值
【发布时间】:2022-11-02 18:12:42
【问题描述】:

我有一个使用 useMemo 将人名转换为两个首字母的组件。

当名称为 Sjaak de Boer 时,我只想测试内容为“SB”。但是 useMemo (或者如果我简单地将其转换为返回函数)很慢,因此测试失败。

codesandbox

import React, { useState, useMemo } from "react";

interface Props {
  name?: string;
}

const ObAvatar: React.FC<Props> = ({ name, ...props }) => {
  const [nameValue, setNameValue] = useState<string>(name);

  const returnInitials = useMemo(() => {
    if ((nameValue && nameValue.length === null) || !nameValue) return "...";
    const rgx: RegExp = new RegExp(/(\p{L}{1})\p{L}+/, "gu");
    const matches: any = nameValue.matchAll(rgx); // fix any!
    let initials: Array<any> = [...matches] || [];
    initials = (
      (initials.shift()?.[1] || "") + (initials.pop()?.[1] || "")
    ).toUpperCase();
    return initials;
  }, [nameValue]);

  return (
    <span style={{ border: "solid 1px red" }} data-testid="initials">
      {returnInitials}
    </span>
  );
};

export default ObAvatar;

我的测试是:

/** @jest-environment jsdom */

import React from "react";
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import Initials from "./Initials";

describe("Initials", () => {
  test("Should render an initials SB (Sjaak de Boer)", () => {
    render(<Initials name="Sjaak de Boer" />);
    const initialsElm: HTMLSpanElement = screen.getByTestId("initials");
    expect(initialsElm).toHaveTextContent(/SB/i);
    screen.debug();
  });
});

我尝试使用计时器,但我觉得我错过了使用 jest 库的某些部分。

【问题讨论】:

    标签: reactjs jestjs jest-dom


    【解决方案1】:

    如果你有一个元素会有延迟,那么你可以使用几个异步函数。当您有一个可能不会立即成立的断言时使用waitFor

    test("Should render an initials SB (Sjaak de Boer)", async () => {
        render(<App name={"Sjaak de Boer"} />);
        const initialsElm: HTMLSpanElement = screen.getByTestId("avatar-initials");
        await waitFor(() => expect(initialsElm).toHaveTextContent(/SB/i));
      });
    

    或者您可以将findByText(或任何findBy* 函数)用于可能不立即存在的元素

    test("Should render an initials SB (Sjaak de Boer)", async () => {
        render(<App name={"Sjaak de Boer"} />);
        const initialsElm: HTMLSpanElement = await screen.findByTestId(/SB/i);
        expect(initialsElm).toBeInTheDocument();
      });
    

    【讨论】:

      猜你喜欢
      • 2018-03-24
      • 2021-12-09
      • 2018-09-15
      • 2020-12-29
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2020-03-24
      相关资源
      最近更新 更多