前言
在Playwright
中,断言是一个非常重要的角色,它可以帮助我们验证页面行为是否符合预期。但是,官方文档中提供的断言API很多,分类也不明确,对于新手来说,根本没办法记住所有。
所以,本文中,我将带着大家一起,系统的学习Playwright
断言API,帮你快速记住。
断言API
Playwright
中提供的断言API很多,但是大致可以分为 基本断言、定位器断言、页面断言、接口类断言等,我们来一个个看下。
基本断言
这些是最基础的断言,通常用于验证元素、页面状态等是否符合预期。
相等:
scss
比较原始类型(如数字、字符串、布尔值),使用 === 运算符进行比较
expect(1).toBe(1); // Passes
比较对象或数组(包括嵌套的属性或元素), 递归地比较对象或数组的每个值
expect({ foo: "bar" }).toEqual({ foo: "bar" }); // Passes
不相等: 在匹配器前面添加 .not
,我们可以预期相反的情况成立:
scss
expect(value).not.toEqual(0);
await expect(locator).not.toContainText('some text');
包含:
scss
expect(value).toContain()
模式匹配:
scss
// 匹配类/基础类型的任何实例
expect(value).any()
// 匹配任何东西
expect(value).anything()
// 数组包含特定元素
expect(value).arrayContaining()
// 数量大致相等
expect(value).closeTo()
// 对象包含特定属性
expect(value).objectContaining()
// 字符串包含子字符串
expect(value).stringContaining()
// 字符串与正则表达式匹配
expect(value).stringMatching()
// 字符串与正则表达式匹配
expect(value).toMatch()
// 对象包含指定的属性
expect(value).toMatchObject()
定位器断言
这些断言主要集中在定位器上,验证元素的状态、属性、样式等与定位器相关的行为。
可见性:
scss
// 元素可见
expect(element).toBeVisible();
// 元素不可见
expect(element).toBeHidden();
// 元素在视图中
expect(element).toBeInViewport();
状态变化:
scss
// 复选框被选中
await expect(locator).toBeChecked();
// 元素已聚焦
await expect(locator).toBeFocused()
// 容器是空的
await expect(locator).toBeEmpty();
// 元素已启用
await expect(locator).toBeEnabled(); //可点
元素内容:
scss
// 元素包含文本
await expect(locator).toContainText(/\d messages/);
// 元素与文本匹配
await expect(locator).toHaveText(/Welcome/);
// 输入有一个值
await expect(locator).toHaveValue(/[0-9]/);
// 元素有一个 ID
await expect(locator).toHaveId('lastname');
// 元素具有类属性
await expect(locator).toHaveClass(/selected/);
页面断言
这些断言主要用于验证页面本身的状态,关注整个页面的行为和外观。
scss
// 页面有一个 URL
await expect(page).toHaveURL()
// 页面有标题
await expect(page).toHaveTitle()
// 页面有截图
await expect(page).toHaveScreenshot()
接口断言
这些断言关注页面或应用程序与外部服务的交互,主要用于验证 HTTP 请求的响应。
scss
await expect(response).toBeOK();
await expect(response).not.toBeOK();
软断言
以上的断言API,在失败的时候,会导致测试终止执行,所以 Playwright
还支持软断言:失败的软断言不会终止测试执行,而是将测试标记为失败。
软断言的使用也很简单,就像这样,使用 .soft
csharp
await expect.soft(page.getByTestId('status')).toHaveText('Success');
以上就是 playwright
中关于断言的API了,大家可以在实际开发过程中,选择合适的断言API,提高测试的质量和效率,确保你的应用程序的稳定性和可靠性。