【发布时间】:2022-11-02 18:12:42
【问题描述】:
我有一个使用 useMemo 将人名转换为两个首字母的组件。
当名称为 Sjaak de Boer 时,我只想测试内容为“SB”。但是 useMemo (或者如果我简单地将其转换为返回函数)很慢,因此测试失败。
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 库的某些部分。
【问题讨论】: