断言
简介
Playwright 包含 Web 特定的断言,它们会自动重试直到满足预期条件。考虑以下示例:
csharp
await Expect(Page.GetByTestId("status")).ToHaveTextAsync("Submitted");Playwright 将重新测试测试 ID 为 status 的元素,直到它具有 "Submitted" 文本。它将重复获取元素并检查,直到满足条件或达到超时。
默认情况下,断言的超时时间为 5 秒。
自动重试的断言
以下断言将重试直到断言通过或达到断言超时。
Expect.ToPassAsync
尽可能优先使用自动重试的断言。对于更复杂的检查,使用 FunctionAssertions.ToPassAsync() 重试代码块直到通过。
csharp
await Expect(async () =>
{
var response = await Page.APIRequest.GetAsync("https://api.example.com");
Assert.AreEqual(200, response.Status);
}).ToPassAsync();你还可以指定自定义超时和重试间隔:
csharp
await Expect(async () =>
{
var response = await Page.APIRequest.GetAsync("https://api.example.com");
Assert.AreEqual(200, response.Status);
}).ToPassAsync(new()
{
// 探测,等待 1 秒,探测,等待 2 秒,探测,等待 10 秒,探测,等待 10 秒,探测
// ... 默认为 [100, 250, 500, 1000]。
Intervals = [1_000, 2_000, 10_000],
Timeout = 60_000,
});默认情况下,ToPassAsync 重试 30 秒。SetDefaultExpectTimeout 不会更改此超时,请改用 SetDefaultExpectToPassTimeout:
csharp
SetDefaultExpectToPassTimeout(60_000);自定义 Expect 消息
你可以指定自定义 expect 消息作为 expect 函数的第二个参数,例如:
csharp
await Expect(Page.GetByText("Name"), "should be logged in").ToBeVisibleAsync();当 expect 失败时,错误将如下所示:
bash
Microsoft.Playwright.PlaywrightAssertionException : should be logged in
Locator expected to be visible
Call log:
- Expect "ToBeVisibleAsync" with timeout 5000ms
- waiting for GetByText("Name")设置自定义超时
你可以全局或按断言指定断言的自定义超时。默认超时为 5 秒。
全局超时
csharp
using Microsoft.Playwright;
using Microsoft.Playwright.MSTest;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PlaywrightTests;
[TestClass]
public class UnitTest1 : PageTest
{
[ClassInitialize]
public static void GlobalSetup(TestContext context)
{
SetDefaultExpectTimeout(10_000);
}
// ...
}按断言超时
csharp
await Expect(Page.GetByText("Name")).ToBeVisibleAsync(new() { Timeout = 10_000 });