Site logo

Fixtures trong Playwright – Chia sẻ và tái sử dụng logic test hiệu quả

5:00 read

Trong quá trình testing, bạn sẽ nhận thấy nhiều đoạn mã lặp lại như authentication, test data, database connections, điều hướng, hoặc thực hiện các tác vụ setup/cleanup. Để tránh lặp lại và dễ dàng quản lý thì ta cần 1 nơi quản lý chung.

Fixtures trong Playwright là cơ chế mạnh mẽ để chia sẻ setup logic, test data và resources giữa các test cases. Chúng giúp test ngắn gọn, ổn định và dễ quản lý.

1. Fixtures là gì?

Fixtures là những objects hoặc services được khởi tạo và cung cấp cho các test. Chúng giúp:

  • Chia sẻ setup logic giữa nhiều tests
  • Cung cấp dữ liệu hoặc trạng thái cần thiết cho test
  • Tự động hóa setup/teardown của resources (browser context, page, database, v.v.)
  • Quản lý lifecycle của resources (tạo và cleanup tự động)
  • Tách biệt test logic khỏi setup code
  • Tái sử dụng code và giảm duplication

Nói 1 cách đơn giản, fixtures là những đối tượng hoặc hàm được khởi tạo trước khi test chạy và có thể được sử dụng trong nhiều test khác nhau. Chúng giúp giảm thiểu việc lặp lại code và đảm bảo rằng các test có cùng một trạng thái ban đầu.

Ví dụ: tạo fixture loggedInPage sẽ cung cấp một page đã đăng nhập sẵn cho các test cần xác thực.

Built-in Fixtures trong Playwright

Playwright cung cấp sẵn nhiều fixtures hữu ích:

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

test('using built-in fixtures', async ({ 
  page,           // Browser page instance
  context,        // Browser context
  browser,        // Browser instance  
  browserName,    // Browser name (chromium, firefox, webkit)
  testInfo        // Test metadata and utilities
}) => {
  console.log(`Running on ${browserName}`);
  console.log(`Test: ${testInfo.title}`);
  
  await page.goto('https://example.com');
  await expect(page).toHaveTitle(/Example/);
});

2. Tạo Custom Fixtures

Basic Custom Fixture

// tests/fixtures/basicFixtures.ts
import { test as baseTest } from '@playwright/test';

// Define fixture types
type CustomFixtures = {
  testUser: {
    email: string;
    password: string;
    name: string;
  };
  apiUrl: string;
};

// Extend base test with custom fixtures
export const test = baseTest.extend<CustomFixtures>({
  // Simple data fixture
  testUser: async ({}, use) => {
    const user = {
      email: 'test@example.com',
      password: 'password123',
      name: 'Test User'
    };
    await use(user);
  },

  // Environment-based fixture
  apiUrl: async ({}, use) => {
    const baseUrl = process.env.API_URL || 'http://localhost:3000';
    await use(`${baseUrl}/api`);
  },
});

export { expect } from '@playwright/test';

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.