End-to-End Testing React Components with Playwright

Posted on: August 26, 2025 10:51 AM

Posted by: Renato

Views: 260

End-to-End Testing React Components with Playwright

Testes de ponta a ponta (E2E) são essenciais para garantir que uma aplicação web se comporte corretamente da perspectiva do usuário. Enquanto os testes unitários e de integração se concentram em partes específicas de uma aplicação, os testes E2E verificam se todo o fluxo da aplicação funciona conforme o esperado. O Playwright, desenvolvido pela Microsoft, é um framework de testes moderno que se destaca na automação de interações do navegador para testes E2E. Este guia se aprofundará em como configurar e utilizar o Playwright para testar componentes React, abrangendo desde a configuração básica até recursos avançados.

1. Introdução ao Playwright

O Playwright é um framework de testes de código aberto projetado para lidar com a complexidade de aplicações web modernas. Ele oferece diversas vantagens para testes E2E:

- Testes Cross-Browser: O Playwright suporta múltiplos navegadores (Chromium, Firefox e WebKit) e permite testes em diferentes plataformas e dispositivos.

- Interação Automatizada: Com o Playwright, você pode simular interações do usuário, como cliques, digitação e envios de formulários. Interceptação de Rede: Simule e inspecione solicitações de rede para simular diferentes respostas do servidor e testar diversos cenários.

- Modo Headless: Execute testes em modo headless (sem interface gráfica do usuário) para execução mais rápida e consumo reduzido de recursos.

2. Configurando o Playwright para um Projeto React Etapa

1: Instalar o Playwright

Para começar, você precisa instalar o Playwright e os binários necessários do navegador. Execute os seguintes comandos no diretório do seu projeto:

npm install --save-dev @playwright/test
npx playwright install
  • @playwright/test: The Playwright test runner package.
  • npx playwright install: Installs the required browser binaries for Playwright to work.

Step 2: Configure Playwright

Create a configuration file named playwright.config.ts in the root of your project. This file defines settings and options for your tests:

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

export default defineConfig({
  projects: [
    {
      name: 'Desktop Chrome',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'Desktop Firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'Desktop Safari',
      use: { ...devices['Desktop Safari'] },
    },
  ],
  use: {
    baseURL: 'http://localhost:3000', // Adjust URL to match your development server
  },
});
  • projects: Defines different browser configurations for testing.
  • use.baseURL: Specifies the base URL for the application being tested.

Step 3: Create Your First Test

Create a test file in the tests directory (or any directory of your choice). For example, create app.spec.ts to write your E2E tests:

import { test, expect } from '@playwright/test';

test('should load the homepage and display the correct content', async ({ page }) => {
  await page.goto('/'); // Uses the baseURL defined in the configuration

  // Check if the page title is correct
  await expect(page).toHaveTitle(/React App/);

  // Check if a specific element is visible
  const header = await page.locator('h1');
  await expect(header).toHaveText('Welcome to React');

  // Simulate a user interaction
  await page.click('button#login');
  await expect(page.locator('text="Login successful"')).toBeVisible();
});

Explanation:

  • page.goto('/'): Navigates to the base URL.
  • expect(page).toHaveTitle: Asserts that the page title matches the expected text.
  • page.locator: Finds elements using CSS selectors.
  • page.click: Simulates a click event.
  • expect(...).toBeVisible(): Asserts that an element is visible.

3. Running Your Tests

To execute your Playwright tests, use the following command:

npx playwright test

This command runs all test files in the tests directory. You can also use additional options:

  • Run in Headless Mode: Tests run without a graphical user interface for faster execution.
  npx playwright test --headless
  • Run in Specific Browser: Execute tests in a specific browser configuration.
  npx playwright test --project=Desktop Chrome
  • Run Tests in Watch Mode: Automatically rerun tests when files change.
  npx playwright test --watch

4. Advanced Testing Scenarios

Network Interception and Mocking

Playwright allows you to intercept network requests and mock responses. This is useful for testing how your application handles different server responses:

import { test, expect } from '@playwright/test';

test('should handle network errors', async ({ page }) => {
  await page.route('**/api/data', (route) =>
    route.fulfill({ status: 500, body: 'Internal Server Error' })
  );

  await page.goto('/');

  // Test behavior when the API returns an error
  await expect(page.locator('text="Error loading data"')).toBeVisible();
});

Explanation:

  • page.route: Intercepts network requests matching the specified pattern.
  • route.fulfill: Mocks a response with a status code and body.

Screenshots and Videos

Capturing screenshots and videos helps in debugging and verifying test results visually:

import { test, expect } from '@playwright/test';

test('should take a screenshot of the homepage', async ({ page }) => {
  await page.goto('/');
  await page.screenshot({ path: 'homepage.png' });
});

Explanation:

  • page.screenshot: Captures a screenshot of the page and saves it to the specified path.

Test Fixtures

Fixtures allow you to set up and tear down common test scenarios, improving test organization:

import { test, expect } from '@playwright/test';

test.describe('User login', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/');
  });

  test('should log in and display user profile', async ({ page }) => {
    await page.fill('input[name="username"]', 'user');
    await page.fill('input[name="password"]', 'password');
    await page.click('button[type="submit"]');
    await expect(page.locator('text="Welcome, user"')).toBeVisible();
  });
});

Explanation:

  • test.beforeEach: Runs before each test in the describe block, setting up the initial state.
  • page.fill: Simulates typing into an input field.

5. Integrating Playwright with CI/CD

Integrating Playwright tests into your Continuous Integration/Continuous Deployment (CI/CD) pipeline ensures that your tests run automatically with every build. Here’s an example configuration for GitHub Actions:

Create a .github/workflows/playwright.yml file:

name: Playwright Tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20'
      - run: npm install
      - run: npx playwright install
      - run: npx playwright test

Explanation:

  • actions/checkout: Checks out the repository.
  • actions/setup-node: Sets up Node.js.
  • npx playwright install: Installs browser binaries.
  • npx playwright test: Runs the Playwright tests.

 

6. Conclusão

O Playwright fornece uma estrutura robusta para testes de ponta a ponta de aplicativos React, permitindo que você verifique se seu aplicativo funciona corretamente em diferentes navegadores e cenários. Sua API poderosa, suporte a vários navegadores e recursos avançados o tornam uma excelente opção para testes web modernos.

Ao integrar o Playwright ao seu fluxo de trabalho, você garante que seu aplicativo React ofereça uma experiência de usuário perfeita, detecte possíveis problemas antecipadamente e mantenha um software de alta qualidade. Para mais informações e recursos avançados, consulte a documentação do Playwright.

https://playwright.dev/

Explore como o Playwright pode aprimorar sua estratégia de testes personalizando sua configuração, aproveitando recursos avançados de teste e integrando-se aos seus pipelines de CI/CD para garantir uma cobertura de teste abrangente e a confiabilidade do aplicativo.

Fonte: https://dev.to/samuel_kinuthia/end-to-end-testing-react-components-with-playwright-part-1-3c15

https://playwright.dev/

https://www.testrigtechnologies.com/blogs/integrating-playwright-with-react/


1

Share

Donate to Site


About Author

Renato

Developer

Add a Comment

Blog Search


Categories

Laravel (227) PHP (151) linux (124) Variados (110) Dicas (58) ubuntu (58) developer (48) postgresql (45) database (44) sql (42) Docker (32) front-end (31) mysql (31) devops (26) webdev (24) programming (23) aws (19) tecnologia (19) eloquent (19) dba (18) OUTROS (17) backend (16) laravelphp (16) debian (12) dev (12) reactjs (10) 100DaysOfCode (10) git (10) react (10) nginx (9) inteligencia-artificial (9) PHP Swoole (9) node (9) javascript (9) linux-tools (8) Architecture (8) vue (7) github (7) ciencia (7) nodejs (6) api (6) vscode (6) webservice (6) jwt (6) vim (6) windows (6) arquitetura (6) authentication (5) ia (5) reactnative (5) rest (5) DevSecOps (5) servers (5) apache (5) macox (5) s3 (5) Kubernetes (4) gitlab (4) opensource (4) mariadb (4) jenkins (4) shell (4) mongodb (4) angular (4) autenticacao (4) wsl (4) Swoole (4) lets-encrypt (4) query (4) Raspberry (4) angularjs (4) inteligenciadedados (4) Padrao de design (4) artigo (4) google (4) npm (4) openai (4) js (3) mysqli (3) Black Hat (3) RabbitMQ (3) educacao (3) intel (3) CMS (2) sail (3) script (3) performance (3) json (3) authorization (3) phpswoole (3) ddd (3) blade (3) terminal (3) log (3) mac (3) fedora (3) containers (3) ssh (3) bash (3) hardware (3) tests (3) macos (3) web (2) jobs (3) websocket (3) db (3) politica (3) Curisidades (2) Solid (2) zsh (2) Go (2) BigLinux (2) POO (2) LazyVim (2) gource (2) Python (2) Oauth2 (2) android (2) unix (2) magento (2) iot (2) ffmpeg (2) combustivel (2) webhook (2) microservices (2) bancodedados (2) tailwind (2) homeOffice (2) html (2) openswoole (2) artificialintelligence (2) security (2) auth (2) cron (2) phpunit (2) kube (2) multiple_authen (2) policia (2) neovim (2) golang (2) noticias (2) livros (2) Transcribe (2) ElonMusk (2) redis (2) claude (2) ArchLinux (2) java (2) saude (1) seguranca (2) phpfpm (2) autorizacao (2) monitoring (2) laptop (2) gnome (2) powerbi (2) telefonia (2) nvm (2) imagick (2) maps (2) colors (2) Passport (2) JQuery (2) front (1) wine (1) covid19 (0) services (1) phpjasper (1) models (1) kali-linux (1) geojson (1) yarn (1) picpay (1) Monolith (1) banco (1) PNPM (1) Desenvolvedor (1) Structurizr (1) symfony (1) presenter (1) lider (1) guard (1) tensorflow (1) bootstrap (1) nuance (1) historia (1) dropbox (1) traefik (1) bug (1) akitando (1) llm (1) htm (1) transformers (1) cavalotroia (1) odd (1) m1 (1) Error (1) cinnamon (1) repmgr (1) federal (1) ruby (1) AppSec (1) orm (1) ArquiteturaDeSoftware (1) Passwordless (1) memcached (1) flow (1) compression (1) athena (1) Migration (1) workflow (1) cqrs (1) kitematic (1) geospacial (1) yeshua (1) data (1) sonarqube (1) Axios (1) pipelines (1) Mozilla (1) kvm (1) GitOps (1) sqlite (1) podcast (1) n8n (1) LaravelFilament (1) God (1) DesenvolvimentoProfissional (1) sw (1) bigtech (1) postgres (1) NoCookies (1) LeetCode (1) governancadedados (1) prf (1) nosql (1) Lideranca (1) Hackers (1) Bots (1) pytorch (1) nuxt (1) liquid (1) ec2 (1) transaction (1) c4 (1) rancher (1) algoritimo (1) Observability (1) Elasticsearch (1) translate (1) certbot (1) Oh My Zsh (1) ibm (1) escopos (1) usb (1) ckeditor (1) API_KEY_GOOGLE_MAPS (1) Manjaro (1) vicuna (1) coding (1) rust (1) markdown (1) JasperReports (1) Fibonacci (1) community (1) Samurai (1) payment (1) messaging (1) Jesus (1) flutter (1) militar (1) fullsta (1) smartphones (1) automacao (1) Monitor (1) zend (1) spaceship (1) PKCE (1) l2tp (1) Glacier (1) laraveloctane (1) Deus (1) binaural (1) gpt (1) bolsonaro (1) privacidade (1) linkedin (1) documentation (1) brain (1) adb (1) nvidia (1) host (1) ecommerce (1) c4-models (1) altadisponibilidade (1) octane (1) lucena (1) http (1) TypeScript (1) chatgpt (1) idiomas (1) eventdrive (1) uuid (1) restfull (1) aplicativo (1) optimization (1) mapas (1) Fetch (1) collections (1) RustLang (1) matematica (1) Filament (1) compactar (1) paypal (1) microg (1) forcas armadas (1) cor (1) auth (1) modelagemdedados (1) k8s (1) gasolina (1) wsl2 (1) csv (1) soap (1) piada (1) KubeCon (1) zorin-os (1) spring-boot (1) backup (1) playwright (1) Deepin (1) storage (1) benchmark (1) networking (1) Swoole (1) biologia (1) node-red (1) LETSENCRYPT (1) Grunt (1) Diagramas (1) boot (1) haru (1) dracula (1) TrabalhoEmEquipe (1) Brasil (1) queue (1) agi (1) llama (1) hotfix (1) economia (1) transcription (1) cache (1) Amazon (1) October (1) lumen (1) Hyperf (1) replication (1) faceapp (1) vala (1) cloudstack (1) rpi (1) apple (1) oracle (1) iode (1) ffaa (1) vpn (1) MeioAmbiente (1) firefox (1) composer (1) scheduling (1) Asahi (1) pendrive (1) microservice (1) front (1) OOD (0) controllers (0)

New Articles



Get Latest Updates by Email