Assertions
Introduction
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 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.
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.
Custom Expect Message
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();
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
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 });