Перейти к содержанию
Skillpedia
Тестирование280k · #239

react-testing

Что он делает

Помогает тестировать программные компоненты, созданные на React. Он проверяет, что они работают так, как ожидает конечный пользователь, то есть что отображается на экране и как пользователь с ними взаимодействует.

Когда использовать

  • ✓При создании новых компонентов React.
  • ✓При исправлении ошибок в существующих компонентах.
  • ✓Чтобы убедиться, что компоненты не сломались после изменений.

Ссылка на скилл

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

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/react-testing/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Протестируй компонент входа, чтобы убедиться, что пользователь может ввести email и пароль и нажать кнопку отправки.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Он использует инструменты, которые имитируют браузер, чтобы отрисовать ваши компоненты и взаимодействовать с ними так, как будто ими пользуется реальный человек. Это помогает находить ошибки до того, как их увидят пользователи.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с 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" />);

…
Частые вопросы

Что такое тесты компонентов?

Это автоматические проверки, которые имитируют использование небольшой части вашего программного обеспечения (компонента), чтобы проверить, ведет ли он себя правильно.

Зачем тестировать то, что видит и делает пользователь?

Тестирование пользовательского опыта гарантирует, что программа полезна и удобна, а не сосредоточена на внутренних деталях, которые могут меняться.

Что значит «мокировать» сетевой запрос?

Это значит имитировать ответ на запрос к интернету. Так можно проверить, как ваш компонент реагирует на разные ответы (успех, ошибка), не используя настоящее подключение.

Подробности

Оригинальное описание автора

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

Популярность

Звёзды на GitHub
280k
Место в рейтинге
#239
Лицензия
MIT
Обновлён
15.10.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы