Chuyển đến nội dung
Skillpedia
Kiểm thử280k · #239

react-testing

Skill này làm gì

Giúp test các thành phần phần mềm xây dựng bằng React. Nó đảm bảo chúng hoạt động như mong đợi đối với người dùng cuối, bằng cách kiểm tra những gì hiển thị trên màn hình và cách người dùng tương tác với chúng.

Khi nào nên dùng

  • ✓Khi tạo thành phần React mới.
  • ✓Khi sửa lỗi trong các thành phần hiện có.
  • ✓Để đảm bảo các thành phần không bị hỏng sau khi thay đổi.

Liên kết skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-testing/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-testing/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Test thành phần đăng nhập để đảm bảo người dùng có thể nhập email và mật khẩu, rồi nhấn nút gửi.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Nó dùng các công cụ mô phỏng trình duyệt để hiển thị thành phần và tương tác với chúng như một người dùng thật. Điều này giúp tìm lỗi trước khi người dùng nhìn thấy.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

React Testing

Comprehensive React testing patterns for behavior-focused component tests, custom hook tests, accessibility assertions, and network-level mocking.

When to Activate

  • Writing tests for React components, custom hooks, or pages
  • Adding test coverage to legacy untested components
  • Migrating from Enzyme or class-component-era patterns to React Testing Library
  • Setting up Vitest or Jest for a new React project
  • Mocking HTTP requests in tests
  • Asserting accessibility violations
  • Deciding which tests belong in RTL vs Playwright Component Testing vs full E2E

Core Principle

Test what the user sees and does, not implementation details.

A test should:

  • Render the component with the same providers it has in production
  • Interact with it via accessible queries (role, label) and userEvent
  • Assert visible output and observable side effects (callback fired, request sent)

A test should NOT:

  • Inspect component state, props passed to children, or which hooks were called
  • Mock React itself or framework hooks
  • Assert on the number of renders or DOM structure beyond what affects users

Library Choice

Runner When Note
Vitest Vite, Remix, modern setups Faster, native ESM, Jest-compatible API
Jest Next.js, CRA, established repos Default for many React projects
Playwright Component Testing Real browser engine needed Use when JSDOM lacks the required feature
Cypress Component Testing Real browser, Cypress already in use Alternative to Playwright CT

Pick one. Do not run RTL + Vitest AND Playwright CT in the same repo unless you have a clear lane separation.

Query Priority

React Testing Library exposes queries in three tiers — use top-down:

  1. Accessible to everyone: getByRole, getByLabelText, getByPlaceholderText, getByText, getByDisplayValue
  2. Semantic: getByAltText, getByTitle
  3. Test IDs (escape hatch): getByTestId
// Best
screen.getByRole("button", { name: /save/i });

// OK for inputs
screen.getByLabelText("Email");

// Last resort
screen.getByTestId("save-btn");

Variants:

  • getBy* — throws if no match
  • queryBy* — returns null (use for "assert absence")
  • findBy* — async, returns a Promise (use for elements that appear after async work)

User Interaction with userEvent

import userEvent from "@testing-library/user-event";

test("submits the form", async () => {
  const user = userEvent.setup();
  const onSubmit = vi.fn();
  render(<UserForm onSubmit={onSubmit} />);

  await user.type(screen.getByLabelText("Email"), "user@example.com");
  await user.click(screen.getByRole("button", { name: /save/i }));

  expect(onSubmit).toHaveBeenCalledWith({ email: "user@example.com" });
});
  • Always await userEvent calls
  • Call userEvent.setup() once per test, reuse the returned user
  • userEvent simulates a real browser sequence; fireEvent dispatches a single synthetic event — prefer userEvent

Async Patterns

// Element that appears after async work
expect(await screen.findByText("Loaded")).toBeInTheDocument();

// Side effect assertion
await waitFor(() => expect(saveSpy).toHaveBeenCalled());

// Element that should disappear
await waitForElementToBeRemoved(() => screen.queryByText("Loading"));

Never setTimeout + assertion — flaky. Use the matchers above.

Network Mocking with MSW

Mock Service Worker mocks at the network layer. The component, hooks, and fetch library all behave exactly as in production.

Setup

// test/setup.ts
import { setupServer } from "msw/node";
import { http, HttpResponse } from "msw";

export const handlers = [
  http.get("/api/users/:id", ({ params }) =>
    HttpResponse.json({ id: params.id, name: "Alice" }),
  ),
  http.post("/api/users", async ({ request }) => {
    const body = await request.json();
    return HttpResponse.json({ id: "new-id", ...body }, { status: 201 });
  }),
];

export const server = setupServer(...handlers);

beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

Configure onUnhandledRequest: "error" so any unmocked request fails the test loudly — silent passes are worse than red.

Per-test override

test("renders error on 500", async () => {
  server.use(
    http.get("/api/users/:id", () => new HttpResponse(null, { status: 500 })),
  );
  render(<UserPage id="1" />);

…
Câu hỏi thường gặp

Component test là gì?

Đây là các kiểm tra tự động mô phỏng việc dùng một phần nhỏ của phần mềm (một thành phần) để xem nó có hoạt động đúng không.

Vì sao test những gì người dùng thấy và làm?

Test trải nghiệm người dùng đảm bảo phần mềm hữu ích và dễ dùng, thay vì chỉ tập trung vào chi tiết nội bộ có thể thay đổi.

'Mocking' một yêu cầu mạng nghĩa là gì?

Nghĩa là mô phỏng một phản hồi cho lời gọi internet. Điều này cho phép test cách thành phần phản ứng với các phản hồi khác nhau (thành công, lỗi) mà không cần kết nối thật.

Chi tiết

Mô tả gốc của tác giả

React component testing with React Testing Library, Vitest/Jest, MSW for network mocking, accessibility assertions with axe, and the decision boundary between component tests and Playwright/Cypress end-to-end runs. Use when writing or fixing tests for React components, hooks, or pages.

repo: affaan-m/ECC

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#239
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự