尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

深入理解 WebdriverIO 的 TypeScript 类型中枢:@wdio/types 全解析

深入理解 WebdriverIO 的 TypeScript 类型中枢:@wdio/types 全解析 深入理解 WebdriverIO 的 TypeScript 类型中枢wdio/types 全解析【免费下载链接】webdriverioNext-gen browser and mobile automation test framework for Node.js项目地址: https://gitcode.com/GitHub_Trending/we/webdriverio导读wdio/types是 WebdriverIO 框架内部的类型定义包它集中存放了 WebdriverIO 各核心模块能力描述 Capabilities、配置选项 Options、服务 Services、框架 Frameworks、报告器 Reporters 等所需的全部 TypeScript 类型。本篇指南以该包的 README 为主体结合仓库源码逐层拆解这些类型束的结构、用途与扩展方式帮助你快速上手在独立项目中复用这些类型并为 WebdriverIO 生态开发自定义服务、报告器或框架适配器时提供类型层面的理论支撑。一、包定位WebdriverIO 的类型中枢WebdriverIO 由数十个 npm 子包组成webdriver、webdriverio、wdio-cli、各 reporter/service 包等它们之间需要共享大量类型定义。与其让每个包各自维护一套WebdriverIO 将类型统一收敛到wdio/types中其 package.json 中的描述也印证了这一点Utility package providing type information for a variety of WebdriverIO interfaces。说明本包主要面向 WebdriverIO内部模块消费但 README 明确说明欢迎在用户自己的 TypeScript 项目中复用这也是本文重点介绍的能力。当前仓库中该包的版本为9.31.2见 package.json要求 Node.js18.20.0以type: module方式发布产物入口为./build/index.d.ts。包内源码由以下文件构成全部位于 packages/wdio-types/src文件职责index.ts总入口汇总导出各类型束及全局命名空间声明Capabilities.ts浏览器/设备能力描述W3C 能力、厂商扩展、Appium 能力等Options.tsWebDriver / WebdriverIO / Testrunner 三层配置选项Services.ts服务与生命周期 Hook 的类型定义Frameworks.tsMocha / Jasmine / Cucumber 框架相关对象类型Reporters.ts报告器选项与实例类型Workers.ts运行器 worker 进程与浏览器运行器消息协议Network.tsWebDriver BiDi 网络请求与 Cookie 类型CustomCommands.ts自定义命令类型Automation.ts自动化协议驱动driver的接口骨架二、安装与基本使用在任意 TypeScript 项目中安装npm i wdio/typeswdio/types只依赖types/node见 package.json因此可以安全地作为开发依赖引入不会带来多余的运行时负担。随后即可像 README 中的示例那样按命名空间导入使用。以能力Capabilities为例import type { Capabilities } from wdio/types; const w3cCaps: Capabilities.W3CCapabilities { alwaysMatch: {}, firstMatch: [], // 以下行会触发编译错误 // Object literal may only specify known properties, // and invalid does not exist in type W3CCapabilities.ts(2322) invalid: 42 }这个示例展示了类型系统的核心价值W3CCapabilities精确约束了 W3C WebDriver 协议中capabilities字段的合法形状——只能包含alwaysMatch与firstMatch两个属性。因此任何拼写错误如示例中的invalid: 42都会在编译期被立即拦截而不是在运行时才由驱动或云端平台报错。三、六大实为九大类型束概览README 明确列出包的几个主要导出束Capabilities、Clients、Options、Services、Frameworks和Reporters并说明其中很多类型与 WebdriverIO 强相关。从 index.ts 源码看实际导出的类型束还包括Workers、Network、CustomCommands和Automationimport type * as Automation from ./Automation.js import type * as Capabilities from ./Capabilities.js import type * as Options from ./Options.js import type * as Services from ./Services.js import type * as Reporters from ./Reporters.js import type * as Frameworks from ./Frameworks.js import type * as Workers from ./Workers.js import type * as Network from ./Network.js import type * as CustomCommands from ./CustomCommands.js export type { Automation, Capabilities, Options, Services, Frameworks, Reporters, Workers, CustomCommands }此外还导出了一组通用工具类型适用于所有模块JsonPrimitive/JsonObject/JsonArray/JsonCompatibleJSON 兼容数据的递归描述FunctionPropertyNamesT/FunctionPropertiesT提取对象中的函数属性ThenArgT解包 Promise 的返回值类型MESSAGE_TYPES常量枚举浏览器运行器的消息类型从Workers.ts导出。这些工具类型在Capabilities.ts的ChromeOptions.prefs、Network.ts的Extensible等场景中被大量复用。四、Capabilities能力描述的完整图景能力Capabilities描述要在哪个浏览器/设备上以何种方式跑测试。Capabilities.ts是全包最大的文件约 1900 行是理解 WebdriverIO 能力体系的最佳入口。4.1 W3C 标准能力WebdriverIO.Capabilities全局接口通过declare global声明覆盖了 W3C WebDriver 规范的全部标准字段字段类型含义browserNamestring用户代理标识chrome/firefox/safari 等browserVersionstring用户代理版本platformNamestring端节点操作系统acceptInsecureCertsboolean导航时是否隐式信任不受信任/自签名的 TLS 证书pageLoadStrategynone \| eager \| normal会话的页面加载策略proxyProxyObject代理配置支持 pac/noproxy/autodetect/system/manual 五种类型及各类代理端口setWindowRectboolean远端是否支持窗口重设/移动命令timeoutsRecordscript \| pageLoad \| implicit, number会话操作超时strictFileInteractabilityboolean严格的文件交互性unhandledPromptBehaviorstring未处理用户提示的行为webSocketUrlboolean是否通过webSocketUrl: true请求双向 WebDriver BiDi 连接在此基础上W3CCapabilities将上述能力包装成协议要求的{ alwaysMatch, firstMatch }结构export interface W3CCapabilities { alwaysMatch: WebdriverIO.Capabilities firstMatch: WebdriverIO.Capabilities[] }4.2 厂商扩展Vendor ExtensionsVendorExtensions接口把各浏览器驱动与云平台的私有能力合入一个巨大的可选字段集见 Capabilities.ts#L281包括Chromegoog:chromeOptions含args、binary、extensions、mobileEmulation、perfLoggingPrefs、prefs、debuggerAddress、Android 包名等大量子字段Firefoxmoz:firefoxOptionsargs、profile、log级别、prefs、Android 相关Edgems:edgeOptions、ms:edgeChromium以及ms:inPrivate等 Edge 能力Safarisafari.optionsAppiumappium:options以及大量带appium:前缀的能力云平台sauce:options、bstack:options、LT:Options/lt:options、tb:options、selenoid:options、moon:options、experitest:accessKeyWebdriverIO 自身wdio:driverPID、wdio:maxInstances、wdio:specs、wdio:exclude、wdio:enforceWebDriverClassic等例如通过wdio:enforceWebDriverClassic: true强制只走经典 WebDriver 协议、不自动切换 BiDi。这里有个值得一提的实现细节RemoveAppiumPrefixT工具类型会从类型键中剥离appium:前缀见 Capabilities.ts#L11AppiumOptions RemoveAppiumPrefix...因此能在不重复定义的情况下让appium:options与顶层appium:xxx能力保持同构。4.3 Appium 移动端能力AppiumCapabilities、AppiumAndroidCapabilities、AppiumXCUITestCapabilities三个接口分别描述 Appium 通用、Android 专用、iOS XCUITest 专用的能力字段。以通用部分为例包含appium:automationNameUiAutomator2 / Espresso / XCUITest 等、appium:platformName、appium:platformVersion、appium:deviceName、appium:app、appium:appPackage、appium:noReset、appium:fullReset、appium:udid、appium:orientation、appium:newCommandTimeout等。Android 部分则细分到appium:adbPort、appium:avd、appium:autoGrantPermissions、appium:isHeadless、appium:unicodeKeyboard等XCUITest 部分包含appium:bundleId、appium:autoAcceptAlerts、appium:wdaLocalPort、appium:usePrebuiltWDA、appium:mjpegServerPort等。源码注释中还标注了大量字段的取值说明与适用平台真实设备/模拟器是移动端能力配置的权威参考。4.4 云平台能力SauceLabsCapabilities、BrowserStackCapabilities、LambdaTestCapabilities、TestingbotCapabilities、SauceLabsVisualCapabilities分别对应各大云测试平台的能力。以 Sauce Labs 为例既有桌面端专属的chromedriverVersion、seleniumVersion、screenResolution、extendedDebugging、capturePerformance也有真实设备专属的cacheId、resigningEnabled、networkCapture、audioCapture等SauceLabsVisualCapabilities则面向视觉回归提供viewportSize、branch、baseBranch、diffOptions、failOnNewStates、scrollAndStitchScreenshots等字段。4.5 多形态的请求能力类型根据使用场景standalone / multiremote / testrunnerCapabilities.ts定义了若干请求侧类型见 Capabilities.ts#L100-L130RequestedStandaloneCapabilities W3CCapabilities | WebdriverIO.Capabilitiesremote()方法可接受的单实例能力RequestedMultiremoteCapabilities以实例名为键、每个值都是完整 WebdriverIO 配置的能力表TestrunnerCapabilitiestestrunner 中capabilities字段的所有合法形态能力数组、多远程能力表或其数组。与之配套的还有三个必填接口WithRequestedCapabilitiesremote()必须提供capabilities、WithRequestedTestrunnerCapabilitiestestrunner 配置必须提供能力数组、WithRequestedMultiremoteCapabilitiesmultiremote 必须提供能力表。它们内部附带的 JSDoc 示例如多浏览器并行、alwaysMatch/firstMatch混用等本身就是可直接借鉴的配置模板。五、Options三层配置选项模型Options.ts 定义了三个逐层叠加的配置接口Connection → WebDriver → WebdriverIO → TestrunnerConnection底层连接选项包括protocol默认http、hostname默认localhost、port、path、queryParams、user/key设置后 WebdriverIO 会自动推导云平台连接地址。WebDriver在连接之上增加logLeveltrace|debug|info|warn|error|silent、logLevels、connectionRetryTimeout默认 120000ms、connectionRetryCount默认 3、bidiResponseTimeout默认 180000ms、headers、transformRequest/transformResponse请求/响应拦截、strictSSL、outputDir、cacheDir、maskingPatterns对日志中敏感信息做**MASKED**掩码替换等。WebdriverIO增加automationProtocol默认webdriver、regionSauce 区域us|eu|...、baseUrl、waitforTimeout默认 5000ms、waitforInterval默认 500ms、maxSpyCollectedBodySizemock命令采集响应体的上限默认 10MB等。Testrunner面向 wdio 测试运行器包含runnerlocal|browserbrowser 表示测试在浏览器内运行、specs/exclude/suites、maxInstances/maxInstancesPerCapability、injectGlobals默认true置为false后需显式import { browser } from wdio/globals、bail、updateSnapshots、specFileRetries系列、services、framework、reporters、mochaOpts/jasmineOpts/cucumberOpts、watch、shard如{ total: 5, current: 2 }、autoXvfb等。另外Options.ts还定义了DefinitionT把配置项描述为{ type, default, required, validate, match }结构、ShardOptions以及 worker 进程生命周期事件RunnerStart/RunnerEnd。六、Services服务与生命周期 HookServices.ts 定义了服务Service的完整契约。服务是替你接管特定杂事、几乎零成本增强测试设置的机制README 之外的官方定位。6.1 服务的四种合法形态ServiceEntry联合类型规定services配置项可以写成四种形式见 Services.ts#L92-L121export type ServiceEntry ( string | // services: [wdio/sauce-service] HookFunctions | // services: [{ onPrepare: () { ... } }] ServiceClass | // services: [CustomClass] [string, WebdriverIO.ServiceOption] | // services: [[wdio/sauce-service, { ... }]] [ServiceClass, WebdriverIO.ServiceOption] // services: [[CustomClass, { ... }]] )这里的关键设计是服务/报告器的选项统一使用WebdriverIO.ServiceOption/WebdriverIO.ReporterOption即Services.ServiceOption/Reporters.Options的全局别名这正是生态包能够扩展他人服务选项的根基——详见下文第八节。6.2 ServiceClass 与 ServicePluginServiceClass是构造函数类型要求new(options, capabilities, config)返回一个ServiceInstance并可选提供静态方法shouldRun在 worker 中构造前运行返回false则跳过该服务。ServicePlugin在此基础上增加default/launcher字段以及shouldLoad静态方法在 launcher 中每包运行一次返回false则 worker 不导入该包。6.3 全量 Hook 函数HookFunctions定义了从onPrepare到afterAssertion的约 20 个生命周期钩子包括运行器级onPrepare所有 worker 启动前、onComplete所有 worker 关闭后抛错将导致测试失败worker 级onWorkerStart、onWorkerEnd会话级before/after、beforeSession/afterSession、onReload用例级beforeSuite/afterSuite、beforeTest/afterTest、beforeHook/afterHook命令与断言级beforeCommand/afterCommand、beforeAssertion/afterAssertion。Hooks类型则把每个 hook 扩展为单函数或函数数组两种写法[k in keyof HookFunctions]: HookFunctions[k] | NonNullableHookFunctions[k][]。七、Frameworks、Reporters 与 Workers7.1 Frameworks框架适配层对象Frameworks.ts 描述 Mocha/Jasmine/Cucumber 三个框架暴露给服务与报告器的对象Suite/Test测试套件与用例含title、file、pending、duration及 Mocha 特有的_currentRetry等TestResult用例结果passed、duration、error、retries、exceptionResults运行器汇总结果finished/passed/failedCucumber 专属Worldpickle 与 result、PickleResult、PickleStepkeyword为Given |When |Then |And 、Tag、Scenario。7.2 Reporters报告器选项与入口Reporters.ts 定义了报告器的选项结构Options包括outputDir、logFile、outputFileFormat自定义日志文件名格式可用cid和capabilities.browserName组合默认wdio-${cid}-${name}-reporter.log、setLogFile、stdout、writeStream并允许第三方报告器通过[key: string]: unknown索引签名自由扩展。ReporterEntry与ServiceEntry同构支持字符串、构造函数、类以及带选项的元组四种写法。7.3 Workersworker 与浏览器运行器消息协议Workers.ts 定义了运行器的进程模型Worker接口一个继承EventEmitter、携带cid/specs/capabilities的 worker 进程、WorkerPool以及一套浏览器运行器wdio/browser-runner与主进程之间的 socket 消息协议。MESSAGE_TYPES枚举consoleMessage、commandRequestMessage、commandResponseMessage、hookTriggerMessage、expectRequestMessage、expectResponseMessage、coverageMap、customCommand、browserTestResult等配合SocketMessagePayload泛型为每类消息定义了严格的载荷类型——例如CommandRequestEvent携带cid、commandName、args与scopeHookResultEvent携带error。index.ts将其作为运行时常量导出export { MESSAGE_TYPES }这在纯类型包里是少见的例外也从侧面说明该协议已深度参与实际运行。八、全局命名空间与生态扩展机制index.tswdio/types最重要的能力之一是全局WebdriverIO命名空间见 index.ts#L43-L103。通过declare global它向整个项目暴露了一组可被各子包**接口合并declaration merging**的空接口或默认接口ServiceOption extends Services.ServiceOption生态服务通过declare module wdio/globals或全局命名空间扩展现有服务选项ReporterOption extends Reporters.Options报告器选项的扩展点MochaOpts/JasmineOpts/CucumberOpts各框架适配器将自己的选项并入从而让mochaOpts等获得精确类型Config extends Options.Testrunner, Capabilities.WithRequestedTestrunnerCapabilitiesWebdriverIO.Config即完整 testrunner 配置RemoteConfig/MultiremoteConfigremote()与 multiremote 模式的配置别名Request extends Network.Request让browser.mock()拦截到的请求对象具备 BiDi 网络类型各 driver 选项接口ChromedriverOptions、GeckodriverOptions含geckoDriverVersion、EdgedriverOptions、SafaridriverOptions统一继承DriverOptionscacheDir/binary/logPath。这正是 README 所说许多类型非常 WebdriverIO 专属的底层含义这些全局接口本身就是 WebdriverIO 生态包服务、报告器、框架适配器彼此类型协作的协议契约。九、实战在 TypeScript 项目中正确消费这些类型9.1 使用WebdriverIO.Config类型化 wdio 配置// wdio.conf.ts import type { Config } from wdio/types export const config: Config { runner: local, specs: [./test/specs/**/*.ts], capabilities: [{ browserName: chrome, goog:chromeOptions: { args: [--headless] } }], // 若字段拼错或类型不符编译期立即报错 maxInstancesPerCapability: 10, framework: mocha, reporters: [spec], mochaOpts: { timeout: 60000 } }9.2 类型化自定义服务的 Hook 与选项编写自定义服务时可直接使用Services.HookFunctions与全局WebdriverIO.ServiceOptionimport type { Services } from wdio/types // 通过接口合并扩展自定义服务选项 declare module wdio/types { namespace WebdriverIO { interface ServiceOption { myServiceToken?: string } } } const myService: Services.ServicePlugin { default: class MyService implements Services.ServiceInstance { constructor(private options: WebdriverIO.ServiceOption) {} onPrepare(config, capabilities) { console.log(token:, this.options.myServiceToken) } } }9.3 复用网络与能力类型处理browser.mock()的响应时可用Network.Request/NetworkCookie标注回调参数校验云端配置时用Capabilities.SauceLabsCapabilities等标注避免sauce:options里出现错别字段需要严格的 W3C 协议结构时用Capabilities.W3CCapabilities即 README 示例的用法。十、延伸阅读类型定义源码packages/wdio-types/src/index.ts、Capabilities.ts、Options.ts、Services.ts消费这些类型的上层实现webdriverio包的 src命令类型、wdio-cli的 src配置解析、wdio-runner的 srcworker/生命周期实际运行示例wdio-local-runner的 src 使用了Workers相关类型wdio-browser-runner的 src 消费了MESSAGE_TYPES消息协议类型演练验证仓库根目录 tests/typings 下的 webdriverio 目录对能力与配置类型做了用例级校验理解wdio/types的结构就等于掌握了 WebdriverIO 各子包之间共享的类型方言——无论是排查编译错误、开发自定义服务/报告器还是深入理解 wdio 配置的每一项含义这个包都是绕不开的权威参考。【免费下载链接】webdriverioNext-gen browser and mobile automation test framework for Node.js项目地址: https://gitcode.com/GitHub_Trending/we/webdriverio创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表