跳至主要內容

參數化測試

您可以使用簡單的 for 迴圈,輕鬆地在測試層級參數化測試,例如

const people = ['Alice', 'Bob']
describe('my tests', () => {
for (const name of people) {
it(`testing with ${name}`, async () => {
// ...
})
}
})

或者透過將測試提取到動態函式中,例如

import { browser } from '@wdio/globals'

function testComponent(componentName, options) {
it(`should test my ${componentName}`, async () => {
await browser.url(`/${componentName}`)
await expect($('input')).toHaveValue(options.expectedValue)
})
}

describe('page components', () => {
testComponent('component-a', { expectedValue: 'some expected value' })
testComponent('component-b', { expectedValue: 'some other expected value' })
})

傳遞環境變數

您可以使用環境變數從命令列設定測試。

例如,考慮以下需要使用者名稱和密碼的測試檔案。通常最好不要將您的秘密儲存在原始碼中,因此我們需要一種從外部傳遞秘密的方式。

it(`example test`, async () => {
// ...
await $('#username').setValue(process.env.USERNAME)
await $('#password').setValue(process.env.PASSWORD)
})

您可以使用在命令列中設定的秘密使用者名稱和密碼來執行此測試。

USERNAME=me PASSWORD=secret npx wdio run wdio.conf.js

同樣地,設定檔也可以讀取透過命令列傳遞的環境變數。

export const config = {
// ...
baseURL: process.env.STAGING === '1'
? 'http://staging.example.test/'
: 'http://example.test/',
// ...
}

現在,您可以針對預備或生產環境執行測試

STAGING=1 npx wdio run wdio.conf.js

.env 檔案

為了更容易管理環境變數,請考慮使用類似 .env 檔案的方式。WebdriverIO 會自動將 .env 檔案載入到您的環境中。您可以定義以下的 .env,而不是將環境變數定義為命令呼叫的一部分

.env
# .env file
STAGING=0
USERNAME=me
PASSWORD=secret

像平常一樣執行測試,您的環境變數應該會被擷取到。

npx wdio run wdio.conf.js

透過 CSV 檔案建立測試

WebdriverIO 測試執行器在 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 'node:fs'
import path from 'node:path'
import { parse } from 'csv-parse/sync'

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

describe('my test suite', () => {
for (const record of records) {
it(`foo: ${record.test_case}`, async () => {
console.log(record.test_case, record.some_value, record.some_other_value)
})
}
})

歡迎!我能如何協助您?

WebdriverIO AI Copilot