ListPager.test.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * D-7/O-3:ListPager 不得在早退后条件性调用 Hook;
  3. * total 从 0 → >0 重渲染必须不抛(硬加载/筛选空态回归)。
  4. */
  5. import { describe, expect, it, vi, afterEach } from "vitest";
  6. import { cleanup, render, screen, act, within } from "@testing-library/react";
  7. import { useState } from "react";
  8. import { ListPager } from "../ListPager";
  9. function Harness({ initialTotal }: { initialTotal: number }) {
  10. const [total, setTotal] = useState(initialTotal);
  11. return (
  12. <div data-testid="pager-harness">
  13. <ListPager total={total} page={0} pageSize={20} onPageChange={() => {}} unit="条" />
  14. <button type="button" onClick={() => setTotal(16)}>fill</button>
  15. </div>
  16. );
  17. }
  18. describe("ListPager Hooks 回归", () => {
  19. afterEach(() => cleanup());
  20. it("total=0 仍展示「共 0 条」", () => {
  21. render(<ListPager total={0} page={0} pageSize={20} onPageChange={() => {}} unit="条" />);
  22. expect(screen.getByText("共 0 条")).toBeTruthy();
  23. });
  24. it("total 从 0 升到有数据时不抛 Hook 错误", () => {
  25. const spy = vi.spyOn(console, "error").mockImplementation(() => {});
  26. render(<Harness initialTotal={0} />);
  27. const root = screen.getByTestId("pager-harness");
  28. expect(within(root).getByText("共 0 条")).toBeTruthy();
  29. act(() => {
  30. within(root).getByRole("button", { name: "fill" }).click();
  31. });
  32. expect(within(root).getByText(/共 16 条/)).toBeTruthy();
  33. const hookNoise = spy.mock.calls.some((args) =>
  34. String(args[0] ?? "").includes("Invalid hook call")
  35. || String(args[0] ?? "").includes("Rules of Hooks")
  36. || String(args[0] ?? "").includes("Rendered more hooks"),
  37. );
  38. expect(hookNoise).toBe(false);
  39. spy.mockRestore();
  40. });
  41. });