Site logo

Test Hooks trong Playwright – Quản lý vòng đời test hiệu quả

5:00 read

Trong quá trình viết test tự động, chúng ta thường cần thực hiện một số tác vụ trước và sau khi chạy test như:

  • Chuẩn bị dữ liệu test
  • Reset trạng thái hệ thống
  • Cleanup sau khi test
  • Setup môi trường test
  • Ghi log và báo cáo

Test Hooks trong Playwright là giải pháp hoàn hảo để quản lý các tác vụ này một cách có tổ chức và hiệu quả.

1. Test Hooks là gì?

Hooks là các hàm chạy trước hoặc sau mỗi test: dùng để chuẩn bị, cleanup, reset state,...

Playwright cung cấp 4 loại hooks chính:

  • beforeEach – chạy trước mỗi test
  • afterEach – chạy sau mỗi test
  • beforeAll – chạy trước toàn bộ test suite
  • afterAll – chạy sau tất cả test

Cấu trúc cơ bản của Test Hooks

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

test.describe('User Management Tests', () => {
  // Chạy trước mỗi test trong describe block
  test.beforeEach(async ({ page }) => {
    console.log('Setting up test environment...');
    // Setup test data
  });

  // Chạy sau mỗi test trong describe block
  test.afterEach(async ({ page }) => {
    console.log('Cleaning up after test...');
    // Cleanup
  });

  // Chạy một lần trước tất cả tests trong describe block
  test.beforeAll(async ({ browser }) => {
    console.log('Setting up test suite...');
    // Global setup
  });

  // Chạy một lần sau tất cả tests trong describe block
  test.afterAll(async () => {
    console.log('Cleaning up test suite...');
    // Global cleanup
  });
});

2. Ví dụ thực tế: Quản lý dữ liệu test

Reset Database trước mỗi test

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

test.describe('User Management', () => {
  test.beforeEach(async ({ page }) => {
    // Reset database trước mỗi test
    await page.request.post('https://api.example.com/test/reset');
  });

  test('Tạo user mới', async ({ page }) => {
    await page.goto('https://dummy-demo-njndex.web.app/users/new');
    await page.fill('[name="email"]', 'test@example.com');
    await page.click('button[type="submit"]');
    await expect(page.locator('text=User created successfully')).toBeVisible();
  });
});

Cleanup sau mỗi test

test.describe('File Upload Tests', () => {
  test.afterEach(async ({ page }) => {
    // Xóa file test sau mỗi test
    await page.request.delete('https://api.example.com/test/files');
  });

  test('Upload file thành công', async ({ page }) => {
    // Test implementation
  });
});

Yêu cầu đăng nhập

Vui lòng đăng nhập để truy cập nội dung này

Additional Resources

Course Guide

Comprehensive PDF guide with examples

GitHub Repository

Example code for all lessons

Discussion

Have a question about this lesson? Post it here and get answers from instructors and peers.