跳到内容
Tauri

WebdriverIO

这个 WebDriver 测试示例将使用 WebdriverIO 及其测试套件。您需要预装 Node.js,以及 npmyarn,尽管最终的示例项目使用了 pnpm

让我们在项目中为这些测试创建一个空间。在这个示例项目中,我们将使用一个嵌套目录,因为我们稍后还会介绍其他框架,但通常你只需要使用一个。使用 mkdir e2e-tests 命令创建我们要使用的目录。本指南的其余部分假设您在 e2e-tests 目录中。

我们将使用一个预先存在的 package.json 文件来启动此测试套件,因为我们已经选择了特定的 WebdriverIO 配置选项,并希望展示一个简单的可行解决方案。本节底部有一个折叠的指南,介绍如何从头开始设置它。

package.json:

{
"name": "webdriverio",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"test": "wdio run wdio.conf.js"
},
"dependencies": {
"@wdio/cli": "^9.19.0"
},
"devDependencies": {
"@wdio/local-runner": "^9.19.0,
"@wdio/mocha-framework": "^9.19.0",
"@wdio/spec-reporter": "^9.19.0"
}
}

我们有一个脚本,将 WebdriverIO 配置作为测试套件运行,并将其公开为 test 命令。我们还有首次设置时由 @wdio/cli 命令添加的各种依赖项。简而言之,这些依赖项用于使用本地 WebDriver 运行器、Mocha 作为测试框架和简单的 Spec Reporter 的最简单设置。

点击此处查看如何从头开始设置项目

CLI 是交互式的,您可以自己选择要使用的工具。请注意,您可能会偏离本指南的其余部分,并且需要自行设置差异。

我们来将 WebdriverIO CLI 添加到此 npm 项目。

npm install @wdio/cli

然后运行交互式配置命令以设置 WebdriverIO 测试套件,您可以运行

npx wdio config

您可能已经注意到,我们 package.json 中的 test 脚本提到了一个文件 wdio.conf.js。这是 WebdriverIO 配置文件,它控制着我们测试套件的大部分方面。

wdio.conf.js:

import os from 'os';
import path from 'path';
import { spawn, spawnSync } from 'child_process';
import { fileURLToPath } from 'url';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
// keep track of the `tauri-driver` child process
let tauriDriver;
let exit = false;
export const config = {
host: '127.0.0.1',
port: 4444,
specs: ['./develop/tests/specs/**/*.js'],
maxInstances: 1,
capabilities: [
{
maxInstances: 1,
'tauri:options': {
application: '../src-tauri/target/debug/tauri-app',
},
},
],
reporters: ['spec'],
framework: 'mocha',
mochaOpts: {
ui: 'bdd',
timeout: 60000,
},
// ensure the rust project is built since we expect this binary to exist for the webdriver sessions
onPrepare: () => {
spawnSync('yarn', ['tauri', 'build', '--debug', '--no-bundle'], {
cwd: path.resolve(__dirname, '..'),
stdio: 'inherit',
shell: true,
});
},
// ensure we are running `tauri-driver` before the session starts so that we can proxy the webdriver requests
beforeSession: () => {
tauriDriver = spawn(
path.resolve(os.homedir(), '.cargo', 'bin', 'tauri-driver'),
[],
{ stdio: [null, process.stdout, process.stderr] }
);
tauriDriver.on('error', (error) => {
console.error('tauri-driver error:', error);
process.exit(1);
});
tauriDriver.on('exit', (code) => {
if (!exit) {
console.error('tauri-driver exited with code:', code);
process.exit(1);
}
});
},
// clean up the `tauri-driver` process we spawned at the start of the session
// note that afterSession might not run if the session fails to start, so we also run the cleanup on shutdown
afterSession: () => {
closeTauriDriver();
},
};
function closeTauriDriver() {
exit = true;
tauriDriver?.kill();
}
function onShutdown(fn) {
const cleanup = () => {
try {
fn();
} finally {
process.exit();
}
};
process.on('exit', cleanup);
process.on('SIGINT', cleanup);
process.on('SIGTERM', cleanup);
process.on('SIGHUP', cleanup);
process.on('SIGBREAK', cleanup);
}
// ensure tauri-driver is closed when our test process exits
onShutdown(() => {
closeTauriDriver();
});

如果您对 config 对象上的属性感兴趣,我们建议阅读文档。对于非 WDIO 特定项,有注释解释了我们为什么要在 onPreparebeforeSessionafterSession 中运行命令。我们还将规范设置为 "./test/specs/**/*.js",现在让我们创建一个规范。

规范包含了测试实际应用程序的代码。测试运行器将加载这些规范并自动运行它们。现在让我们在我们指定的目录中创建规范。

test/specs/example.e2e.js:

// calculates the luma from a hex color `#abcdef`
function luma(hex) {
if (hex.startsWith('#')) {
hex = hex.substring(1);
}
const rgb = parseInt(hex, 16);
const r = (rgb >> 16) & 0xff;
const g = (rgb >> 8) & 0xff;
const b = (rgb >> 0) & 0xff;
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
describe('Hello Tauri', () => {
it('should be cordial', async () => {
const header = await $('body > h1');
const text = await header.getText();
expect(text).toMatch(/^[hH]ello/);
});
it('should be excited', async () => {
const header = await $('body > h1');
const text = await header.getText();
expect(text).toMatch(/!$/);
});
it('should be easy on the eyes', async () => {
const body = await $('body');
const backgroundColor = await body.getCSSProperty('background-color');
expect(luma(backgroundColor.parsed.hex)).toBeLessThan(100);
});
});

顶部的 luma 函数只是我们其中一个测试的辅助函数,与应用程序的实际测试无关。如果您熟悉其他测试框架,您可能会注意到暴露了类似的功能,例如 describeitexpect。其他 API,例如 $ 及其暴露的方法,都涵盖在 WebdriverIO API 文档中。

现在我们已经设置好配置和规范,让我们运行它!

npm test

我们应该看到以下输出:

➜ webdriverio git:(main) ✗ yarn test
yarn run v1.22.11
$ wdio run wdio.conf.js
Execution of 1 workers started at 2021-08-17T08:06:10.279Z
[0-0] RUNNING in undefined - /develop/tests/specs/example.e2e.js
[0-0] PASSED in undefined - /develop/tests/specs/example.e2e.js
"spec" Reporter:
------------------------------------------------------------------
[wry 0.12.1 linux #0-0] Running: wry (v0.12.1) on linux
[wry 0.12.1 linux #0-0] Session ID: 81e0107b-4d38-4eed-9b10-ee80ca47bb83
[wry 0.12.1 linux #0-0]
[wry 0.12.1 linux #0-0] » /develop/tests/specs/example.e2e.js
[wry 0.12.1 linux #0-0] Hello Tauri
[wry 0.12.1 linux #0-0] ✓ should be cordial
[wry 0.12.1 linux #0-0] ✓ should be excited
[wry 0.12.1 linux #0-0] ✓ should be easy on the eyes
[wry 0.12.1 linux #0-0]
[wry 0.12.1 linux #0-0] 3 passing (244ms)
Spec Files: 1 passed, 1 total (100% completed) in 00:00:01
Done in 1.98s.

我们看到 Spec Reporter 告诉我们 test/specs/example.e2e.js 文件中的所有 3 个测试都已通过,以及最终报告 Spec Files: 1 passed, 1 total (100% completed) in 00:00:01

使用 WebdriverIO 测试套件,我们只需几行配置和一条命令即可轻松为我们的 Tauri 应用程序启用端到端测试!更好的是,我们根本不必修改应用程序。


© 2025 Tauri 贡献者。CC-BY / MIT