Skip to content

React 组件测试

使用 @testing/library-react

安装

sh
npm install --save-dev @testing-library/react

配置

WARNING

将配置从 vite.config.ts 中抽离,单独写一个 vitest.config.ts

ts
import tsconfigPaths from "vite-tsconfig-paths";
import { defineConfig } from "vitest/config";

export default defineConfig({
  plugins: [
    tsconfigPaths(),
  ],
  test: {
    globals: true,
    environment: "jsdom",
    setupFiles: "./app/__tests__/setup.js",
  },
});

初始化 setup.js 文件

js
import { afterEach } from "vitest";
import { cleanup } from "@testing-library/react";
import "@testing-library/jest-dom/vitest";

afterEach(() => {
  cleanup();
});

第一个测试用例

ts
import { expect, it } from "vitest";
import "@testing-library/jest-dom/vitest";
import { render, screen } from "@testing-library/react";

// component
import Footer from "../../../components/common/Footer";

describe("test Footer component", () => {
  let remix: any;
  beforeEach(() => {
    render(<Footer />);
    remix = screen.getByText(/Remix/i);
  });

  it("Footer remix element and attribute", () => {
    expect(remix.tagName).toBe("A");
    expect(remix.getAttribute("href")).toBe("https://remix.run/");
    expect(remix).toBeInTheDocument();
  });

  it("Footer remix Snapshot", () => {
    expect(remix).toMatchInlineSnapshot(`
      <a
        class="ant-pro-global-footer-list-link"
        href="https://remix.run/"
        rel="noreferrer"
        target="_blank"
        title="Remix"
      >
        Remix
      </a>
    `);
  });
});