Langsung ke konten
Skillpedia
Testing280k ยท #239

react-testing

Fungsinya

Membantu menguji komponen perangkat lunak yang dibangun dengan React. Tool ini memastikan komponen berfungsi sebagaimana mestinya bagi pengguna akhir, dengan memeriksa apa yang ditampilkan di layar dan bagaimana pengguna berinteraksi dengannya.

Kapan dipakai

  • โœ“Saat membuat komponen React baru.
  • โœ“Saat memperbaiki masalah pada komponen yang sudah ada.
  • โœ“Untuk memastikan komponen tidak rusak setelah ada perubahan.

Link skill

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

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-testing/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit โ†’

Contoh permintaan ke AI

โ€œUji komponen login untuk memastikan pengguna bisa mengetik email dan password lalu mengklik tombol submit.โ€

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Tool ini menggunakan alat yang meniru browser untuk merender komponen Anda dan berinteraksi dengannya, seolah-olah pengguna sungguhan sedang menggunakannya. Cara ini membantu menemukan error sebelum pengguna melihatnya.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari GitHub.

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" />);

โ€ฆ
Pertanyaan umum

Apa itu component tests?

Ini adalah pemeriksaan otomatis yang mensimulasikan penggunaan bagian kecil dari perangkat lunak Anda (sebuah komponen) untuk melihat apakah ia berperilaku dengan benar.

Mengapa menguji apa yang dilihat dan dilakukan pengguna?

Menguji pengalaman pengguna memastikan perangkat lunak bermanfaat dan mudah digunakan, daripada hanya berfokus pada detail internal yang mungkin berubah.

Apa arti 'mocking' sebuah network request?

Artinya mensimulasikan respons untuk sebuah panggilan internet. Dengan cara ini, Anda bisa menguji bagaimana komponen bereaksi terhadap respons yang berbeda (berhasil, gagal) tanpa perlu koneksi sungguhan.

Detail

Deskripsi asli dari pembuat

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

Popularitas

Bintang GitHub
280k
Peringkat
#239
Lisensi
MIT
Diperbarui
15/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • โ€ฆ

Skill lain dari repositori ini

Skill serupa