Aller au contenu principal
ProduitsOutils de bureauTASTECADConsultation de plansTASTEFILESGestion de fichiersTASTEFTPTransfert de fichiersTASTESSHEspace de travail à distanceTASTEZIPCompression et extractionTASTEWINMGestion de fichiersOutils pour développeursTASTECODEEnvironnement de développement intégré pour RustTASTESTUDIOEnvironnement intégré de développement et de testTASTEETLIntégration de données (ETL)ServeursTASTEREMOTEServeur de bureau à distanceTASTEGEOServeur géospatialTASTEMAILEspace de travail e-mailInvestissementTASTESTOCKApplication de bureau de trading automatique d'actionsCommencerTéléchargementsDocumentationAcheterTous les produits
Marketplace
Actualités
TechActualitésL’actu dev du jourDocs développeursLangages de programmationRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks d'applications et de bureauTauriFlutterReact NativeElectronAlgorithmesBases des algorithmesAlgorithmes essentielsAlgorithmes avancésAlgorithmes pratiques
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrineGuide de la communauté
CollaborerTransfert techniqueRéalisation de site webRéalisation d'application de bureauChaîne de publication et de paiementPartenaire commercialContact
ServicesBureau à distancePaquets d'installation sur mesure
TASTEDEV
Produits

Outils de bureau

TASTECADDes plans complexes, ouverts en toute légèretéTASTEFILESSeulement les fichiers utiles, au plus viteTASTEFTPLe chemin le plus net pour vos fichiersTASTESSHEntre vos serveurs et vous, un lien plus solideTASTEZIPCompresser plus vite, extraire en toute sécuritéTASTEWINMUn gestionnaire de fichiers à deux volets, pensé pour le clavier

Outils pour développeurs

TASTECODEModifier, compiler, déboguer et tester vos apps Rust dans une seule fenêtreTASTESTUDIODe l’édition aux tests à distance et aux corrections IA approuvéesTASTEETLDéplacer les données, les valeurs sous les yeux

Serveurs

TASTEREMOTEUn bureau à distance hébergé sur votre propre serveurTASTEGEOUn serveur géospatial compatible GeoServer, reconstruit en RustTASTEMAILReprenez la maîtrise de vos e-mails

Investissement

TASTESTOCKDu trading automatique d'actions selon vos règles : quand, et quoi

Commencer

TéléchargementsDernières versions de chaque produitDocsUtiliser chaque produitAcheterAbonnements et licences perpétuellesTous les produitsTous les produits en un coup d’œil
Tous les produits
MarketplaceActualités
Tech

Actualités

L’actu dev du jourAnnonces officielles : langages, frameworks, GitHub et IADocs développeursGuides des langages, frameworks et algorithmes

Langages de programmation

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks d'applications et de bureauTauriFlutterReact NativeElectron

Algorithmes

Bases des algorithmesAnalyse de complexité · Tri · Recherche · Structures de données de base · Arbres et tasAlgorithmes essentielsParcours de graphe · Plus courts chemins et arbres couvrants · Programmation dynamique · Algorithmes gloutons · Diviser pour régner · Backtracking (retour sur trace)Algorithmes avancésAlgorithmes sur les chaînes · Mathématiques et théorie des nombres · Manipulation de bits · Arbres de segments · Union-FindAlgorithmes pratiquesStratégie pour les entretiens de codage · Cache LRU · Limitation de débit · Hachage cohérent
Toute la documentation de développement
Communauté
ProjetsDécouvrir les créateurs et leurs travauxJournaux de développementDécisions et enseignementsPromptsInstructions réutilisablesProblèmes d’outils d’IAProblèmes et contournements de Claude, Codex, GeminiVitrineRéalisations terminéesGuide de la communautéConstruire en toute transparence
Collaborer
Transfert techniqueApplications natives en Rust et eguiRéalisation de site web10 langues, comptes, documentation et téléchargementsRéalisation d'application de bureauRust et egui, sans WebViewChaîne de publication et de paiementSignature, MSI, deb, rpm, AppImage, empreintesPartenaire commercialRecommandez-nous, touchez 30 %ContactDéveloppement, partenariats, investissement
Services
Bureau à distanceAccédez à votre ordinateur depuis le navigateurPaquets d'installation sur mesureSeulement l'utile, réglages préchargés
Acheter
FR
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Se connecter
Se connecter
TASTEDEV

Des petits outils à un meilleur développement.

support@tastedev.netSoutenir TASTEDEV
ProduitsGamme de produitsAcheterDocsTéléchargementsMarketplaceAssistance
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrine
RèglesÀ proposPolitique de confidentialitéConditions d'utilisationConditions d’abonnementRemboursementRègles de la communauté
CompteSe connecterS'inscrire
Visiteurs
Aujourd’hui
Hier
Vues au total
Société
GXSOFT
Représentant
CHOI YOUNG GU
Numéro d’enregistrement
853-44-00368
Adresse
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Téléphone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsable de la confidentialité
CHOI YOUNG GU

© 2026 TASTEDEVLes informations produit s'appuient sur des sources de développement vérifiées.Publié · en amélioration

Documentation React
React
Getting Started with ReactProject StructureCore ConceptsData and StateTestingBuild and Deployment
Discussions

Guide React · 5/6

Testing

Ce chapitre n'est disponible qu'en anglais pour le moment.

Tests for a React app usually come in two layers. Components and hooks are checked quickly with Vitest and React Testing Library, while complete user flows run in a real browser with Playwright.

Installing Vitest and React Testing Library

Vitest reuses your Vite configuration, so it needs almost no extra transform setup. Install it together with jsdom, which emulates the browser DOM, and the Testing Library packages.

npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event @testing-library/jest-dom

Add a test section to vite.config.ts. The reference comment at the top lets TypeScript know about the test field.

/// <reference types="vitest/config" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  test: {
    environment: "jsdom",
    globals: true,
    setupFiles: "./src/test/setup.ts",
    include: ["src/**/*.test.{ts,tsx}"],
  },
});

With globals: true, Testing Library automatically cleans up rendered output after each test. Setting include keeps Vitest from picking up the Playwright tests you will add later. The setup file src/test/setup.ts registers DOM-specific matchers such as toBeInTheDocument().

import "@testing-library/jest-dom/vitest";

Finally, add "test": "vitest" to the scripts in package.json. npm test runs in watch mode and re-runs related tests on every save; in CI, run once with npx vitest run.

Testing components

Testing Library steers you toward testing what the user sees rather than implementation details. Find elements by accessible information such as getByRole or getByLabelText whenever possible, and simulate clicks and typing with user-event, which mimics real user interaction closely.

// src/Counter.tsx
import { useState } from "react";

export function Counter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}
// src/Counter.test.tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import { Counter } from "./Counter";

describe("Counter", () => {
  it("increments when clicked", async () => {
    const user = userEvent.setup();
    render(<Counter />);

    const button = screen.getByRole("button", { name: "Clicked 0 times" });
    await user.click(button);

    expect(button).toHaveTextContent("Clicked 1 times");
  });
});
Des questions sur ce chapitre ?
Chapitre précédentData and StateChapitre suivantBuild and Deployment

Async UI and mocks

Components that load data should receive mocked responses instead of hitting the network. Replace the global fetch with vi.spyOn, and use findBy... queries, which wait for elements that appear later. The UserName component from the previous chapter serves as the example.

import { render, screen } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { UserName } from "./UserName";

afterEach(() => {
  vi.restoreAllMocks();
});

it("loads and shows the user's name", async () => {
  vi.spyOn(globalThis, "fetch").mockResolvedValue(
    new Response(JSON.stringify({ id: 1, name: "Ada" })),
  );

  render(<UserName userId={1} />);

  expect(screen.getByText("Loading…")).toBeInTheDocument();
  expect(await screen.findByText("Ada")).toBeInTheDocument();
});

For apps with many API calls, Mock Service Worker (MSW) intercepts requests at the network level, so tests and the dev server can share the same mock API.

Testing custom hooks

To test a hook without any UI, use renderHook. Wrap calls that update state in act so React applies every update before you assert on the result.

import { act, renderHook } from "@testing-library/react";
import { expect, it } from "vitest";
import { useTodos } from "./useTodos";

it("adds a todo", () => {
  const { result } = renderHook(() => useTodos());

  act(() => result.current.add("Buy milk"));

  expect(result.current.todos).toHaveLength(1);
  expect(result.current.todos[0].text).toBe("Buy milk");
});

End-to-end tests with Playwright

Playwright launches real Chromium, Firefox and WebKit browsers and drives your app the way a user would. The init command creates the config file and an example test, and installs the browsers in one go.

npm init playwright@latest

Setting webServer in playwright.config.ts starts the dev server automatically before the tests run.

import { defineConfig, devices } from "@playwright/test";

export default defineConfig({
  testDir: "./e2e",
  use: { baseURL: "http://localhost:5173" },
  webServer: {
    command: "npm run dev",
    url: "http://localhost:5173",
    reuseExistingServer: !process.env.CI,
  },
  projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
});
// e2e/counter.spec.ts (assumes the home page renders Counter)
import { expect, test } from "@playwright/test";

test("the counter button works", async ({ page }) => {
  await page.goto("/");
  await page.getByRole("button", { name: /Clicked/ }).click();
  await expect(page.getByRole("button", { name: "Clicked 1 times" })).toBeVisible();
});

Run the suite with npx playwright test; add --ui to step through each action with a live view while debugging. Playwright's expect retries until the condition holds, so there is no need for arbitrary sleeps.

Summary

  • Test components and hooks with Vitest and React Testing Library, and full browser flows with Playwright.
  • Find elements by role and label, and simulate interaction with user-event.
  • Wait for async results with findBy... queries, and mock the network with vi.spyOn or MSW.
  • Playwright's webServer option starts the dev server automatically for end-to-end runs.

0 commentaire

Meilleurs commentairesPlus récents d'abord

Se connecter · Connectez-vous pour laisser un commentaire.