断言
WDIO 测试运行器内置了一个断言库,允许您对浏览器或Web应用程序中的元素进行强大的断言。它扩展了Jest Matchers的功能,增加了为端到端测试优化的匹配器,例如:
const $button = await $('button')
await expect($button).toBeDisplayed()
或者
const selectOptions = await $$('form select>option')
// 确保select中至少有一个选项
await expect(selectOptions).toHaveChildren({ gte: 1 })
完整列表请参见expect API 文档。
软断言
WebdriverIO 从 expect-webdriver(5.2.0) 开始默认包含软断言。软断言允许您的测试在断言失败时继续执行。所有失败都会被收集并在测试结束时报告。
使用方法
// 这些断言失败时不会立即抛出错误
await expect.soft(await $('h1').getText()).toEqual('Basketball Shoes');
await expect.soft(await $('#price').getText()).toMatch(/€\d+/);
// 常规断言仍然会立即抛出错误
await expect(await $('.add-to-cart').isClickable()).toBe(true);
从 Chai 迁移
Chai 和 expect-webdriverio 可以共存,通过一些小调整可以平滑过渡到 expect-webdriverio。如果您已升级到 WebdriverIO v6,那么默认情况下您可以直接使用 expect-webdriverio 的所有断言。这意味着在任何地方使用 expect 时,您都会调用 expect-webdriverio 断言。除非您将 injectGlobals 设置为 false 或明确地覆盖了全局 expect 以使用 Chai。在这种情况下,没有明确导入 expect-webdriverio 包,您将无法访问任何 expect-webdriverio 断言。
本指南将展示如果 Chai 在本地被覆盖以及如果 Chai 在全局被覆盖时如何迁移的示例。