断言
介绍
🌐 Introduction
Playwright 包含针对网页的断言,这些断言会自动重试,直到满足预期条件。看看下面的例子:
🌐 Playwright includes web-specific assertions that automatically retry until the expected condition is met. Consider the following example:
await Expect(Page.GetByTestId("status")).ToHaveTextAsync("Submitted");
Playwright 会一直重新测试测试 ID 为 status 的元素,直到它显示 "Submitted" 文本。它会不断重新获取元素并检查,直到条件满足或超时。
🌐 Playwright will re-test the element with the test ID of status until it has the "Submitted" text. It will re-fetch the element and check it repeatedly until the condition is met or the timeout is reached.
默认情况下,断言的超时时间是5秒。
🌐 By default, the timeout for assertions is 5 seconds.
自动重试断言
🌐 Auto-retrying assertions
以下断言会一直重试,直到断言通过或达到断言超时时间。
🌐 The following assertions will retry until the assertion passes or the assertion timeout is reached.
自定义 Expect 消息
🌐 Custom Expect Message
你可以将自定义的期望消息作为第二个参数传递给 expect 函数,例如:
🌐 You can specify a custom expect message as a second argument to the expect function, for example:
await Expect(Page.GetByText("Name"), "should be logged in").ToBeVisibleAsync();
当 Expect 失败时,错误将如下所示:
🌐 When expect fails, the error would look like this:
Microsoft.Playwright.PlaywrightException : should be logged in
Locator expected to be visible
Call log:
- Expect "ToBeVisibleAsync" with timeout 5000ms
- waiting for GetByText("Name")
设置自定义超时
🌐 Setting a custom timeout
你可以为断言指定自定义超时时间,既可以全局设置,也可以针对单个断言设置。默认超时时间为 5 秒。
🌐 You can specify a custom timeout for assertions either globally or per assertion. The default timeout is 5 seconds.
全局超时
🌐 Global timeout
- MSTest
- NUnit
- xUnit
- xUnit v3
using Microsoft.Playwright;
using Microsoft.Playwright.NUnit;
using NUnit.Framework;
namespace PlaywrightTests;
[Parallelizable(ParallelScope.Self)]
[TestFixture]
public class Tests : PageTest
{
[OneTimeSetUp]
public void GlobalSetup()
{
SetDefaultExpectTimeout(10_000);
}
// ...
}
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);
}
// ...
}
using Microsoft.Playwright;
using Microsoft.Playwright.Xunit;
namespace PlaywrightTests;
public class UnitTest1: PageTest
{
UnitTest1()
{
SetDefaultExpectTimeout(10_000);
}
// ...
}
using Microsoft.Playwright;
using Microsoft.Playwright.Xunit.v3;
namespace PlaywrightTests;
public class UnitTest1: PageTest
{
UnitTest1()
{
SetDefaultExpectTimeout(10_000);
}
// ...
}
每个断言超时
🌐 Per assertion timeout
await Expect(Page.GetByText("Name")).ToBeVisibleAsync(new() { Timeout = 10_000 });