參數化測試
簡介
你可以在測試層級或專案層級對測試進行參數化。
參數化測試
[
{ name: 'Alice', expected: 'Hello, Alice!' },
{ name: 'Bob', expected: 'Hello, Bob!' },
{ name: 'Charlie', expected: 'Hello, Charlie!' },
].forEach(({ name, expected }) => {
// You can also do it with test.describe() or with multiple tests as long the test name is unique.
test(`testing with ${name}`, async ({ page }) => {
await page.goto(`https://example.com/greet?name=${name}`);
await expect(page.getByRole('heading')).toHaveText(expected);
});
});
Before and after hooks
大多數情況下,你應該將 beforeEach
、beforeAll
、afterEach
和 afterAll
鉤子放在 forEach
之外,這樣鉤子只會執行一次:
test.beforeEach(async ({ page }) => {
// ...
});
test.afterEach(async ({ page }) => {
// ...
});
[
{ name: 'Alice', expected: 'Hello, Alice!' },
{ name: 'Bob', expected: 'Hello, Bob!' },
{ name: 'Charlie', expected: 'Hello, Charlie!' },
].forEach(({ name, expected }) => {
test(`testing with ${name}`, async ({ page }) => {
await page.goto(`https://example.com/greet?name=${name}`);
await expect(page.getByRole('heading')).toHaveText(expected);
});
});
如果你想為每個測試設置鉤子,你可以將它們放在 describe()
中 - 這樣它們會在每次迭代 / 每個單獨的測試中執行:
[
{ name: 'Alice', expected: 'Hello, Alice!' },
{ name: 'Bob', expected: 'Hello, Bob!' },
{ name: 'Charlie', expected: 'Hello, Charlie!' },
].forEach(({ name, expected }) => {
test.describe(() => {
test.beforeEach(async ({ page }) => {
await page.goto(`https://example.com/greet?name=${name}`);
});
test(`testing with ${expected}`, async ({ page }) => {
await expect(page.getByRole('heading')).toHaveText(expected);
});
});
});
參數化專案
Playwright Test 支援同時執行多個測試專案。在以下範例中,我們將使用不同的選項執行兩個專案。
我們宣告選項 person
並在配置中設定值。第一個專案使用值 Alice
,第二個使用值 Bob
。
- TypeScript
- JavaScript
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 }],
});
const base = require('@playwright/test');
exports.test = base.test.extend({
// Define an option and provide a default value.
// We can later override it in the config.
person: ['John', { option: true }],
});
我們可以在測試中使用這個選項,類似於 fixtures。
import { test } from './my-test';
test('test 1', async ({ page, person }) => {
await page.goto(`/index.html`);
await expect(page.locator('#node')).toContainText(person);
// ...
});
現在,我們可以通過使用項目在多種配置中執行測試。
- TypeScript
- JavaScript
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' },
},
]
});
// @ts-check
module.exports = defineConfig({
projects: [
{
name: 'alice',
use: { person: 'Alice' },
},
{
name: 'bob',
use: { person: 'Bob' },
},
]
});
我們也可以在一個固定裝置中使用該選項。了解更多關於固定裝置。
- TypeScript
- JavaScript
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 }],
// Override default "page" fixture.
page: async ({ page, person }, use) => {
await page.goto('/chat');
// We use "person" parameter as a "name" for the chat room.
await page.getByLabel('User Name').fill(person);
await page.getByText('Enter chat room').click();
// Each test will get a "page" that already has the person name.
await use(page);
},
});
const base = require('@playwright/test');
exports.test = base.test.extend({
// Define an option and provide a default value.
// We can later override it in the config.
person: ['John', { option: true }],
// Override default "page" fixture.
page: async ({ page, person }, use) => {
await page.goto('/chat');
// We use "person" parameter as a "name" for the chat room.
await page.getByLabel('User Name').fill(person);
await page.getByText('Enter chat room').click();
// Each test will get a "page" that already has the person name.
await use(page);
},
});
參數化專案的行為在 1.18 版中已更改。了解更多。
傳遞環境變數
您可以使用環境變數從命令列配置測試。
例如,考慮以下需要用戶名和密碼的測試文件。通常來說,不將你的秘密儲存在源程式碼中是個好主意,所以我們需要一種方法從外部傳遞秘密。
test(`example test`, async ({ page }) => {
// ...
await page.getByLabel('User Name').fill(process.env.USER_NAME);
await page.getByLabel('Password').fill(process.env.PASSWORD);
});
你可以在命令列中設定你的秘密使用者名稱和密碼來執行這個測試。
- Bash
- PowerShell
- Batch
USER_NAME=me PASSWORD=secret npx playwright test
$env:USER_NAME=me
$env:PASSWORD=secret
npx playwright test
set USER_NAME=me
set PASSWORD=secret
npx playwright test
同樣地,設定檔也可以讀取通過命令列傳遞的環境變數。
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: process.env.STAGING === '1' ? 'http://staging.example.test/' : 'http://example.test/',
}
});
現在,你可以對測試環境或生產環境執行測試:
- Bash
- PowerShell
- Batch
STAGING=1 npx playwright test
$env:STAGING=1
npx playwright test
set STAGING=1
npx playwright test
.env files
為了更容易管理環境變數,可以考慮使用 .env
檔案。這裡有一個範例,使用 dotenv
套件直接在配置檔案中讀取環境變數。
import { defineConfig } from '@playwright/test';
import dotenv from 'dotenv';
import path from 'path';
// Read from ".env" file.
dotenv.config({ path: path.resolve(__dirname, '.env') });
// 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
文件來設定你想要的任何變數。
# .env file
STAGING=0
USER_NAME=me
PASSWORD=secret
如往常一樣執行測試,你的環境變數應該會被拾取。
npx playwright test
建立測試透過 CSV 檔案
Playwright 測試執行器在 Node.js 中執行,這意味著您可以直接從檔案系統讀取檔案並使用您偏好的 CSV 函式庫解析它們。
請參見此 CSV 文件,在我們的範例 input.csv
中:
"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"
根據這個,我們將使用來自 NPM 的 csv-parse 函式庫生成一些測試:
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);
});
}