Học Playwright tiếng Việt, Cộng đồng Playwright cho người Việt

Vọc Vạch Playwright

[Vọc Playwright] Test use options

https://playwright.dev/docs/test-use-options

Giới thiệu

  • Để cấu hình nâng cao hơn cho test runner, bạn cũng cần config Emulation, Network, Recording cho Browser hoặc BrowserContext.
  • Các cấu hình này được cài đặt ở trong use: {} ở file test.

Option cơ bản

  • Có 2 option: baseURL và storageState.
OptionDescription
testOptions.baseURLĐường dẫn mặc định cho tất cả các page, sử dụng trong hàm goto nếu chỉ dùng path. VD: nếu base URL là https://playwrightvn.wordpress.com/, thì dùng page.goto(‘/lesson10’) sẽ tự động được hiểu là: https://playwrightvn.wordpress.com/lesson10
testOptions.storageStateMở các trang web với một storage state (đại khái là load dữ liệu của một phiên làm việc trước khi chạy test). Đặc biệt thường dùng khi làm các test case đăng nhập

Emulation (Giả lập)

  • Playwright cho phép bạn giả lập các thiết bị thật như điện thoại hay máy tính bảng.
  • Bạn có thể giả lập:
  • geolocation: vị trí địa lý
  • locale
  • timezone
  • permission: cài đặt quyền cho browser
  • colorScheme: giao diện tối hay sáng.
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    // Emulates `'prefers-colors-scheme'` media feature.
    colorScheme: 'dark',

    // Context geolocation.
    geolocation: { longitude: 12.492507, latitude: 41.889938 },

    // Emulates the user locale.
    locale: 'en-GB',

    // Grants specified permissions to the browser context.
    permissions: ['geolocation'],

    // Emulates the user timezone.
    timezoneId: 'Europe/Paris',

    // Viewport used for all pages in the context.
    viewport: { width: 1280, height: 720 },
  },
});
OptionMô tả
testOptions.colorSchemeCho phép tùy chọn theme. Các option là: ‘light’, ‘dark’, ‘no-preference’
testOptions.geolocationVị trí địa lý. Nhìn ví dụ trên bạn có thể thấy đó là kinh độ và vĩ độ.
testOptions.localeLocale code, kiểu mã quốc gia. VD: en-GB, de-DE, vi-VN, etc.
testOptions.permissionsCác quyền cấp cho trình duyệt. Ví dụ muốn trình duyệt mặc định đã được cấp quyền access location thì ghi vào đây.
testOptions.timezoneIdThay đổi timezone (múi giờ).
testOptions.viewportThay đổi kích thước viewport. (có thể tạm hiểu là kích thước màn hình cũng được.

Network (mạng)

  • Bạn cũng có thể cài đặt network cho các test:
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    // Whether to automatically download all the attachments.
    acceptDownloads: false,

    // An object containing additional HTTP headers to be sent with every request.
    extraHTTPHeaders: {
      'X-My-Header': 'value',
    },

    // Credentials for HTTP authentication.
    httpCredentials: {
      username: 'user',
      password: 'pass',
    },

    // Whether to ignore HTTPS errors during navigation.
    ignoreHTTPSErrors: true,

    // Whether to emulate network being offline.
    offline: true,

    // Proxy settings used for all pages in the test.
    proxy: {
      server: 'http://myproxy.com:3128',
      bypass: 'localhost',
    },
  },
});
OptionMô tả
testOptions.acceptDownloadsCho phép dơwnload tự động
testOptions.extraHTTPHeadersHeader thêm vào cho mỗi request
testOptions.httpCredentialsThông tin đăng nhapaj
testOptions.ignoreHTTPSErrorsBỏ qua lỗi https khi navigate
testOptions.offlineSetting offline
testOptions.proxySetting proxy. Kiểu bạn muốn trình duyệt sử dụng proxy nào đó để chạy test trong mạng nội bộ chẳng hạn.

Recording options

  • With Playwright you can capture screenshots, record videos as well as traces of your test. By default these are turned off but you can enable them by setting the screenshot, video and trace options in your playwright.config.js file.
  • Trace files, screenshots and videos will appear in the test output directory, typically test-results.
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    // Capture screenshot after each test failure.
    screenshot: 'only-on-failure',

    // Record trace only when retrying a test for the first time.
    trace: 'on-first-retry',

    // Record video only when retrying a test for the first time.
    video: 'on-first-retry'
  },
});
OptionDescription
testOptions.screenshotCapture screenshots of your test. Options include ‘off’, ‘on’ and ‘only-on-failure’
testOptions.tracePlaywright can produce test traces while running the tests. Later on, you can view the trace and get detailed information about Playwright execution by opening Trace Viewer. Options include: ‘off’, ‘on’, ‘retain-on-failure’ and ‘on-first-retry’
testOptions.videoPlaywright can record videos for your tests. Options include: ‘off’, ‘on’, ‘retain-on-failure’ and ‘on-first-retry’

Other Options

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

export default defineConfig({
  use: {
    // Maximum time each action such as `click()` can take. Defaults to 0 (no limit).
    actionTimeout: 0,

    // Name of the browser that runs tests. For example `chromium`, `firefox`, `webkit`.
    browserName: 'chromium',

    // Toggles bypassing Content-Security-Policy.
    bypassCSP: true,

    // Channel to use, for example "chrome", "chrome-beta", "msedge", "msedge-beta".
    channel: 'chrome',

    // Run browser in headless mode.
    headless: false,

    // Change the default data-testid attribute.
    testIdAttribute: 'pw-test-id',
  },
});
OptionDescription
testOptions.actionTimeoutTimeout for each Playwright action in milliseconds. Defaults to 0 (no timeout). Learn more about timeouts and how to set them for a single test.
testOptions.browserNameName of the browser that runs tests. Defaults to ‘chromium’. Options include chromium, firefox, or webkit.
testOptions.bypassCSPToggles bypassing Content-Security-Policy. Useful when CSP includes the production origin. Defaults to false.
testOptions.channelBrowser channel to use. Learn more about different browsers and channels.
testOptions.headlessWhether to run the browser in headless mode meaning no browser is shown when running tests. Defaults to true.
testOptions.testIdAttributeChanges the default data-testid attribute used by Playwright locators.

More browser and context options

  • Any options accepted by browserType.launch() or browser.newContext() can be put into launchOptions or contextOptions respectively in the use section.
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    launchOptions: {
      slowMo: 50,
    },
  },
});
  • However, most common ones like headless or viewport are available directly in the use section – see basic options, emulation or network.

Explicit Context Creation and Option Inheritance

  • If using the built-in browser fixture, calling browser.newContext() will create a context with options inherited from the config:
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    userAgent: 'some custom ua',
    viewport: { width: 100, height: 100 },
  },
});

Trả lời