测试技巧·续1
// card.jsimport React, { useEffect } from "react";export default function Card(props) { useEffect(() => { const timeoutID = setTimeout(() => { props.onSelect(null); }, 5000); return () => { clearTimeout(timeoutID); }; }, [props.onSelect]); return [1, 2, 3, 4].map(choice => ( <button key={choice} data-testid={choice} onClick={() => props.onSelect(choice)} > {choice} </button> ));}
我们可以利用 Jest 的计时器 mock 为这个组件编写测试,并测试它可能处于的不同状态。
// card.test.jsimport React from "react";import { render, unmountComponentAtNode } from "react-dom";import { act } from "react-dom/test-utils";import Card from "./card";let container = null;beforeEach(() => { // 创建一个 DOM 元素作为渲染目标 container = document.createElement("div"); document.body.appendChild(container); jest.useFakeTimers();});afterEach(() => { // 退出时进行清理 unmountComponentAtNode(container); container.remove(); container = null; jest.useRealTimers();});it("超时后应选择 null", () => { const onSelect = jest.fn(); act(() => { render(<Card onSelect={onSelect} />, container); }); // 提前 100 毫秒执行 act(() => { jest.advanceTimersByTime(100); }); expect(onSelect).not.toHaveBeenCalled(); // 然后提前 5 秒执行 act(() => { jest.advanceTimersByTime(5000); }); expect(onSelect).toHaveBeenCalledWith(null);});it("移除时应进行清理", () => { const onSelect = jest.fn(); act(() => { render(<Card onSelect={onSelect} />, container); }); act(() => { jest.advanceTimersByTime(100); }); expect(onSelect).not.toHaveBeenCalled(); // 卸载应用程序 act(() => { render(null, container); }); act(() => { jest.advanceTimersByTime(5000); }); expect(onSelect).not.toHaveBeenCalled();});it("应接受选择", () => { const onSelect = jest.fn(); act(() => { render(<Card onSelect={onSelect} />, container); }); act(() => { container .querySelector("[data-testid='2']") .dispatchEvent(new MouseEvent("click", { bubbles: true })); }); expect(onSelect).toHaveBeenCalledWith(2);});
你只能在某些测试中使用假计时器。在上面,我们通过调用 jest.useFakeTimers() 来启用它们。它们提供的主要优势是,你的测试实际上不需要等待 5 秒来执行,而且你也不需要为了测试而使组件代码更加复杂。
快照测试
像 Jest 这样的框架还允许你使用 toMatchSnapshot / toMatchInlineSnapshot 保存数据的“快照”。有了这些,我们可以“保存”渲染的组件输出,并确保对它的更新作为对快照的更新显式提交。
在这个示例中,我们渲染一个组件并使用 pretty 包对渲染的 HTML 进行格式化,然后将其保存为内联快照:
// hello.test.js, againimport React from "react";import { render, unmountComponentAtNode } from "react-dom";import { act } from "react-dom/test-utils";import pretty from "pretty";import Hello from "./hello";let container = null;beforeEach(() => { // 创建一个 DOM 元素作为渲染目标 container = document.createElement("div"); document.body.appendChild(container);});afterEach(() => { // 退出时进行清理 unmountComponentAtNode(container); container.remove(); container = null;});it("应渲染问候语", () => { act(() => { render(<Hello />, container); }); expect( pretty(container.innerHTML) ).toMatchInlineSnapshot(); /* ... 由 jest 自动填充 ... */ act(() => { render(<Hello name="Jenny" />, container); }); expect( pretty(container.innerHTML) ).toMatchInlineSnapshot(); /* ... 由 jest 自动填充 ... */ act(() => { render(<Hello name="Margaret" />, container); }); expect( pretty(container.innerHTML) ).toMatchInlineSnapshot(); /* ... 由 jest 自动填充 ... */});
通常,进行具体的断言比使用快照更好。这类测试包括实现细节,因此很容易中断,并且团队可能对快照中断不敏感。选择性地 mock 一些子组件可以帮助减小快照的大小,并使它们在代码评审中保持可读性。
多渲染器
在极少数情况下,你可能正在使用多个渲染器的组件上运行测试。例如,你可能正在使用 react-test-renderer 组件上运行快照测试,该组件内部使用子组件内部的 ReactDOM.render 渲染一些内容。在这个场景中,你可以使用与它们的渲染器相对应的 act() 来包装更新。
import { act as domAct } from "react-dom/test-utils";import { act as testAct, create } from "react-test-renderer";// ...let root;domAct(() => { testAct(() => { root = create(<App />); });});expect(root).toMatchSnapshot();
缺少什么?
如果有一些常见场景没有覆盖,请在文档网站的 issue 跟踪器上告诉我们。
