テストのパラメータ化
テストレベルで、単純な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)
})
このテストは、コマンドラインで秘密のユーザー名とパスワードを設定して実行できます。
- Bash
- Powershell
- Batch
USERNAME=me PASSWORD=secret npx wdio run wdio.conf.js
$env:USERNAME=me
$env:PASSWORD=secret
npx wdio run wdio.conf.js
set USERNAME=me
set PASSWORD=secret
npx wdio run wdio.conf.js
同様に、設定ファイルもコマンドラインから渡された環境変数を読み取ることができます。
export const config = {
// ...
baseURL: process.env.STAGING === '1'
? 'http://staging.example.test/'
: 'http://example.test/',
// ...
}
これで、ステージング環境または本番環境に対してテストを実行できます。
- Bash
- Powershell
- Batch
STAGING=1 npx wdio run wdio.conf.js
$env:STAGING=1
npx wdio run wdio.conf.js
set 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)
})
}
})