
par Zelkulon17 mars 20251 min de lecture
Playwright est le framework de test E2E le plus puissant. De l'installation à des tests robustes et maintenables – avec des exemples Next.js et une intégration CI/CD.
Playwright vs. Cypress
Playwright: Cypress: ────────────────────────────────── ────────────────────────────────── ✓ Chromium, Firefox, WebKit ✗ Principalement Chromium ✓ Multi-Tab/Multi-Window ✗ Pas de vrais multi-onglets ✓ Vraie parallélisation ✗ Seulement avec le plan Enterprise ✓ Trace-Viewer (debug voyage dans le temps) ✗ Uniquement vidéo/captures ✓ TypeScript nativ ✓ Oui
Configuration
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
reporter: [['html'], ['github']],
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'mobile', use: { ...devices['iPhone 14'] } },
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
});Locators stables
// Bonne pratique : locators basés sur les rôles (sémantiques, stables)
page.getByRole('button', { name: 'Absenden' });
page.getByRole('heading', { name: 'Kontakt' });
page.getByLabel('Deine E-Mail-Adresse');
page.getByPlaceholder('[email protected]');
page.getByTestId('submit-button'); // data-testid="..."
// Acceptable
page.getByText('Mehr erfahren');
// Éviter : classes CSS (cassent lors du refactoring)
page.locator('.btn-primary');
// Jamais : XPath
page.locator('xpath=//div[3]/button[1]');Tester un formulaire
test('soumet le formulaire de contact avec succès', async ({ page }) => {
await page.goto('/de/contact');
await page.getByLabel('Dein Name').fill('Max Muster');
await page.getByLabel('E-Mail').fill('[email protected]');
await page.getByLabel('Nachricht').fill('Testnachricht.');
await page.getByRole('button', { name: 'Absenden' }).click();
await expect(page.getByText(/Danke für deine Nachricht/))
.toBeVisible({ timeout: 10_000 });
});
test('affiche les erreurs de validation sur un formulaire vide', async ({ page }) => {
await page.goto('/de/contact');
await page.getByRole('button', { name: 'Absenden' }).click();
await expect(page.getByText(/Name ist erforderlich/)).toBeVisible();
});Mocking d'API
test('affiche une erreur en cas de panne API', async ({ page }) => {
// simuler une erreur API
await page.route('**/api/blog/posts*', async route => {
await route.fulfill({ status: 500 });
});
await page.goto('/de/blog');
await expect(page.getByText(/Fehler beim Laden/)).toBeVisible();
});Page Object Model
// e2e/pages/BlogPage.ts
export class BlogPage {
constructor(private readonly page: Page) {}
async goto(locale = 'de') {
await this.page.goto(`/${locale}/blog`);
}
async search(query: string) {
await this.page.getByPlaceholder('Artikel suchen...').fill(query);
await this.page.keyboard.press('Enter');
}
async getArticleCount() {
return this.page.locator('[data-testid="blog-card"]').count();
}
}
// Utilisation dans le test
test('recherche des articles', async ({ page }) => {
const blogPage = new BlogPage(page);
await blogPage.goto();
await blogPage.search('Spring Boot');
expect(await blogPage.getArticleCount()).toBeGreaterThan(0);
});CI/CD – GitHub Actions
# .github/workflows/e2e.yml
- name: Install Playwright browsers
run: npx playwright install --with-deps
- name: Run E2E tests
run: npx playwright test
env:
CI: true
- name: Upload test report
uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-report
path: playwright-report/Conclusion
- Fiable : l'attente automatique des éléments élimine les tests instables
- Rapide : vraie parallélisation, pas de surcharge navigateur
- Déboguable : Trace Viewer transforme le débogage en voyage dans le temps
- Complet : tests de captures d'écran, mocking d'API, multi-navigateurs
- Conseil : couvrir uniquement les parcours utilisateur critiques, pas chaque clic