如何扩展WebdriverIO V9 Capabilities以添加自定义参数
正确扩展WebdriverIO V9 Capabilities添加自定义参数的实现方法
1. 扩展Capabilities的TypeScript类型
直接在Capabilities中添加自定义字段会触发TypeScript类型错误,需要先扩展WebdriverIO的Capabilities接口。在项目根目录创建wdio.d.ts文件:
declare module '@wdio/types' { interface Capabilities { testCaseId?: number; testRunId?: number; } } export {};
该文件会让TypeScript识别自定义的Capabilities字段,避免类型校验报错。
2. 在配置文件中给Capabilities注入自定义参数
修改wdio.conf.ts,将自定义参数直接写入capabilities数组的浏览器配置对象中,替代之前单独的customParams字段:
export const config: WebdriverIO.Config = { runner: "local", tsConfigPath: "./tsconfig.json", specs: ["./test/specs/**/*.ts"], exclude: [], maxInstances: 10, capabilities: [ { browserName: "chrome", testCaseId: 1, testRunId: 1 } ], after: function (result, capabilities, specs) { // 可直接访问自定义参数,无类型错误 console.log("testCaseId:", capabilities.testCaseId); console.log("testRunId:", capabilities.testRunId); } };
3. 在自定义Reporter中获取Capabilities的自定义参数
调整custom-reporter.ts,从测试统计对象或Runner统计对象中读取包含自定义参数的Capabilities:
import WDIOReporter from "@wdio/reporter"; import type { Reporters, Capabilities } from "@wdio/types"; import type TestStats from "@wdio/reporter/build/stats/test"; export default class CustomReporter extends WDIOReporter { constructor(options: Partial<Reporters.Options>) { options = Object.assign(options, { stdout: true }); super(options); } async onTestPass(test: TestStats) { this.write(`Congratulations! Your test "${test.title}" passed 👏`); // 从测试统计对象中获取Capabilities及自定义参数 const capabilities = test.capabilities as Capabilities; console.log("testCaseId in reporter:", capabilities.testCaseId); console.log("testRunId in reporter:", capabilities.testRunId); } async onRunnerStart(runnerStats) { // 从Runner启动统计中获取Capabilities const capabilities = runnerStats.capabilities as Capabilities; console.log("Runner start testCaseId:", capabilities.testCaseId); } }
核心要点
- 自定义参数直接嵌入Capabilities对象,确保所有钩子(onPrepare、before、after、onComplete)都能通过公共的capabilities实例访问到参数。
- 通过扩展TypeScript接口解决类型报错,这是规范的类型扩展方式,避免使用强制类型断言的不严谨写法。
- 若需为多浏览器实例配置不同参数,只需在capabilities数组的不同对象中分别设置
testCaseId和testRunId即可。
内容的提问来源于stack exchange,提问作者veenaMSL
相关产品推荐
相关产品推荐

