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

Vọc Vạch Playwright

[Vọc Playwright] Tham số hoá test

https://playwright.dev/docs/test-parameterize

Giới thiệu

  • Parameterize tests, hay tham số hoá test là việc bạn tạo ra các test dựa trên một danh sách các giá trị.

Tham số hoá test

  • Ví dụ:
// example.spec.ts

const people = ['Alice', 'Bob'];
for (const name of people) {
  test(`testing with ${name}`, async () => {
    // ...
  });
  // You can also do it with test.describe() or with multiple tests as long the test name is unique.
}

  • Bạn có thể tham số hoá ở cấp độ project và cấp độ test.

Tham số hoá project

  • Xét đoạn code sau:
import { test as base } from '@playwright/test';

export type TestOptions = {
  person: string;
};

export const test = base.extend<TestOptions>({
  // Define an option and provide a default value.
  // We can later override it in the config.
  person: ['John', { option: true }],
});
  • Ở đoạn code trên đang định nghĩa một thuộc tính person có default value là John. Thuộc tính này sẽ được ghi đè bởi project phía dưới.
  • Tiếp tục vào tới file test:
import { test } from './my-test';

test('test 1', async ({ page, person }) => {
  await page.goto(`/index.html`);
  await expect(page.locator('#node')).toContainText(person);
  // ...
});
  • Và cuối cùng là config:
import { defineConfig } from '@playwright/test';
import type { TestOptions } from './my-test';

export default defineConfig<TestOptions>({
  projects: [
    {
      name: 'alice',
      use: { person: 'Alice' },
    },
    {
      name: 'bob',
      use: { person: 'Bob' },
    },
  ]
});
  • Hiểu đơn giản là test sẽ chạy theo từng project khác nhau, mỗi project một giá trị.
  • Cũng chưa biết ứng dụng thực tế trong trường hợp nào !? Maybe có thể trong case test nội dung mail thì các trình duyệt có thể hiển thị khác nhau. Gắn cờ isSupportFrame hoặc gì đó vào trong project chẳng hạn.

Truyền biến môi trường

  • Đơn giản là dùng process.env
test(`example test`, async ({ page }) => {
  // ...
  await page.getByLabel('User Name').fill(process.env.USER_NAME);
  await page.getByLabel('Password').fill(process.env.PASSWORD);
});
  • Lúc chạy thì dùng thế này:
USER_NAME=me PASSWORD=secret npx playwright test
  • File config cũng có thể đọc được biến môi trường
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    baseURL: process.env.STAGING === '1' ? 'http://staging.example.test/' : 'http://example.test/',
  }
});

.env file

  • Thường thì không ai pass biến môi trường vào command cả. Chúng ta thường dùng file .env. Tất nhiên phải cài package dotenv để hỗ trợ đọc file .env và đưa thành biến môi trường.
import { defineConfig } from '@playwright/test';
import dotenv from 'dotenv';
import path from 'path';

// Read from default ".env" file.
dotenv.config();

// Alternatively, read from "../my.env" file.
dotenv.config({ path: path.resolve(__dirname, '..', 'my.env') });

export default defineConfig({
  use: {
    baseURL: process.env.STAGING === '1' ? 'http://staging.example.test/' : 'http://example.test/',
  }
});
  • .env file
# .env file
STAGING=0
USER_NAME=me
PASSWORD=secret

Tạo test bằng file CSV

  • Ở một số nơi, còn gọi đây là “data driven” test.
  • Ví dụ có file csv như sau:
"test_case","some_value","some_other_value"
"value 1","value 11","foobar1"
"value 2","value 22","foobar21"
"value 3","value 33","foobar321"
"value 4","value 44","foobar4321"
  • Sử dụng thư viện csv-parse, bạn có thể tạo test như sau:
    • Đọc file csv
    • Chạy vòng for, trong vòng for tạo test mới
import fs from 'fs';
import path from 'path';
import { test } from '@playwright/test';
import { parse } from 'csv-parse/sync';

const records = parse(fs.readFileSync(path.join(__dirname, 'input.csv')), {
  columns: true,
  skip_empty_lines: true
});

for (const record of records) {
  test(`foo: ${record.test_case}`, async ({ page }) => {
    console.log(record.test_case, record.some_value, record.some_other_value);
  });
}

Trả lời