Site logo
Tác giả
  • avatar Nguyễn Đức Xinh
    Name
    Nguyễn Đức Xinh
    Twitter
Ngày xuất bản
Ngày xuất bản

Tìm Hiểu Playwright Screenshots và Videos

Giới thiệu về Screenshots và Videos trong Playwright

Playwright cung cấp hai tính năng mạnh mẽ để capture và ghi lại quá trình test execution: ScreenshotsVideos. Hai tính năng này đóng vai trò quan trọng trong việc debugging, documentation và monitoring test results.

Screenshots trong Playwright

Cách sử dụng cơ bản

Đây là cách nhanh nhất để chụp screenshot và lưu vào file:

await page.screenshot({ path: 'screenshot.png' });

Screenshots API cung cấp nhiều parameters cho image format, clip area, quality và các tuỳ chọn khác.

Full Page Screenshots

Full page screenshot là screenshot của toàn bộ trang có thể scroll, như thể bạn có một màn hình rất cao và trang có thể fit hoàn toàn trong đó.

await page.screenshot({ path: 'screenshot.png', fullPage: true });

Element Screenshots

Bạn có thể chụp screenshot của một element cụ thể:

await page.locator('.header').screenshot({ path: 'screenshot.png' });

Capture vào Buffer

Thay vì ghi vào file, bạn có thể lấy buffer với image và xử lý sau hoặc truyền cho third party pixel diff facility:

const buffer = await page.screenshot();
console.log(buffer.toString('base64'));

Screenshots API Parameters

Screenshots API hỗ trợ nhiều options quan trọng:

await page.screenshot({
  path: 'screenshot.png',
  fullPage: true,              // Chụp toàn bộ trang có thể scroll
  clip: { x: 0, y: 0, width: 800, height: 600 }, // Crop area cụ thể
  quality: 80,                 // Chất lượng cho JPEG (0-100)
  type: 'png',                 // 'png' | 'jpeg'
  animations: 'disabled',       // 'allow' | 'disabled'
  caret: 'hide',               // 'hide' | 'initial'
  scale: 'css',                // 'css' | 'device'
  mask: [page.locator('.ads')] // Mask sensitive elements
});

Videos trong Playwright

Giới thiệu về Video Recording

Playwright có thể record videos cho các tests. Tính năng này giúp debug và review test results hiệu quả.

Cấu hình Video Recording

Playwright Test có thể record videos cho tests, được điều khiển bởi option video trong Playwright config. Mặc định videos sẽ tắt.

// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    video: 'on-first-retry',
  },
});

Sử dụng Video Recording trong Test

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

test.use({
  video: "on",
});

test.describe("Authentication Flow", () => {
  test("should successfully sign up a new user", async ({ page }) => {
    // 
  })
});

Các chế độ Video Recording

Có 4 chế độ recording chính:

Mode Mô tả
'off' Không record video
'on' Record video cho mỗi test
'retain-on-failure' Record video cho mỗi test, nhưng xóa tất cả videos từ successful test runs
'on-first-retry' Chỉ record video khi retry test lần đầu tiên

Cấu hình Video Size

Bạn cũng có thể chỉ định video size. Video size mặc định là viewport size được scale down để fit 800x800:

// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    video: {
      mode: 'on-first-retry',
      size: { width: 640, height: 480 }
    }
  },
});

Multi-page Scenarios

Đối với multi-page scenarios, bạn có thể truy cập video file liên quan đến page thông qua page.video():

const path = await page.video().path();

Lưu ý: Video chỉ available sau khi page hoặc browser context được đóng.

Video files sẽ xuất hiện trong test output directory, thường là test-results. Videos được lưu khi browser context closure ở cuối test.

Ví dụ thực tế sử dụng Screenshots và Videos

Test case với cả Screenshots và Videos

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

test.describe('E-commerce checkout flow', () => {
  test.use({ 
    video: 'retain-on-failure',
    screenshot: 'only-on-failure'
  });

  test('complete purchase flow', async ({ page }) => {
    // Navigate to product page
    await page.goto('https://example-shop.com/products/laptop');
    
    // Take screenshot of product page
    await page.screenshot({ path: 'product-page.png' });
    
    // Add to cart
    await page.click('[data-testid="add-to-cart"]');
    
    // Screenshot of cart
    await page.locator('.cart-summary').screenshot({ 
      path: 'cart-summary.png' 
    });
    
    // Proceed to checkout
    await page.click('[data-testid="checkout"]');
    
    // Fill checkout form
    await page.fill('[name="email"]', 'test@example.com');
    await page.fill('[name="address"]', '123 Test Street');
    
    // Screenshot before payment
    await page.locator('.checkout-form').screenshot({ 
      path: 'checkout-form.png' 
    });
    
    // Complete payment
    await page.click('[data-testid="complete-payment"]');
    
    // Verify success and take final screenshot
    await expect(page.locator('.success-message')).toBeVisible();
    await page.screenshot({ path: 'purchase-success.png' });
  });
});

Tối ưu hóa cho CI/CD Pipelines

Cấu hình cho Môi trường CI/CD

// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    // Chỉ record video khi test fail để tiết kiệm storage
    video: process.env.CI ? 'retain-on-failure' : 'on-first-retry',
    
    // Screenshot chỉ khi fail
    screenshot: process.env.CI ? 'only-on-failure' : 'on',
  },
  
  // Cấu hình cho các môi trường khác nhau
  projects: [
    {
      name: 'chromium',
      use: { 
        ...devices['Desktop Chrome'],
        // Giảm video size cho CI
        video: process.env.CI ? { 
          mode: 'retain-on-failure',
          size: { width: 640, height: 480 }
        } : 'on-first-retry'
      },
    },
  ],
});

Kết luận

Screenshots và Videos là những công cụ mạnh mẽ trong Playwright giúp cải thiện quá trình debugging và documentation của các tests. Bằng cách tận dụng các tính năng này, bạn có thể nâng cao chất lượng và hiệu quả của quy trình kiểm thử tự động. Hãy áp dụng các kỹ thuật và best practices đã trình bày để tối ưu hóa việc sử dụng Screenshots và Videos trong dự án của bạn.