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 في هذا الرابط ونفّذ تعليماته لمهمتي.
تريد أن يجد الذكاء الاصطناعي مهارات مثل هذه بنفسه؟ثبّت خادم Skillpedia MCP المجاني: سطر واحد، ويبحث في 15,000+ مهارة قبل كل مهمة.ثبّته في دقيقة واحدة →

مثال على ما تطلبه من الذكاء الاصطناعي

“اختبر مكوّن تسجيل الدخول للتأكد من أن المستخدم يستطيع كتابة البريد الإلكتروني وكلمة المرور، ثم النقر على زر الإرسال.”

5 مهارات جديدة كل أسبوع. قراءة في دقيقة واحدة.

كيف تعمل

تستخدم أدوات تحاكي المتصفح لعرض المكونات والتفاعل معها كما لو كان المستخدم الحقيقي يستخدمها. وهذا يساعد على اكتشاف الأخطاء قبل أن يراها المستخدمون.

المحتوى التقني (ملف 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" />);

…
الأسئلة الشائعة

ما هي اختبارات المكونات؟

هي فحوص آلية تحاكي استخدام جزء صغير من برنامجك (مكوّن) للتحقق من أنه يتصرف بشكل صحيح.

لماذا نختبر ما يراه المستخدم ويفعله؟

اختبار تجربة المستخدم يضمن أن البرنامج مفيد وسهل الاستخدام، بدلًا من التركيز على التفاصيل الداخلية التي قد تتغير.

ماذا يعني «محاكاة» طلب الشبكة (mocking)؟

يعني محاكاة استجابة لطلب من الإنترنت. وهذا يتيح اختبار كيفية تفاعل المكوّن مع الاستجابات المختلفة (نجاح، خطأ) دون الحاجة إلى اتصال حقيقي.

التفاصيل

الوصف الأصلي من المؤلف

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

سجّل الدخول للتصويت.

التعليقات

  • …

المزيد من المهارات من هذا المستودع

مهارات مشابهة