End-to-end tests with Playwright¶
This page sets the rules for browser tests written with Playwright in ConnectSoft repositories and in applications generated from ConnectSoft templates. It is written for engineers who write or review end-to-end steps. Following it gives tests that fail only when the product is wrong, and that say why when they fail.
The test stack is set by CS-TST-001: Playwright with Microsoft.Playwright.MSTest.v4, or plain Microsoft.Playwright driven from Reqnroll hooks in a suite written as Gherkin features. The general rules for deterministic tests are in CS-TST-007; this page adds what they mean in a browser.
How end-to-end tests go wrong¶
Most end-to-end failures that are not product defects belong to one of three families:
- Timing. The test acts before the page is ready, or waits for something that is not the real signal. A Blazor Server page is prerendered: its controls are visible and enabled before the circuit connects, and a click on such a control is accepted by the DOM and discarded without an error.
- False oracles. The assertion is satisfied whatever the server did. Asserting a select's value right after selecting it, or asserting that a row is absent with a selector that never matches, proves nothing.
- Shared state. Two suites sign in as the same users, or a test consumes data that it never gives back.
A test that passes alone and fails in the full suite almost always has one of these problems. Run the scenario alone first. If it passes alone, fix the wait or the oracle in the test before you read the product code. Do not retry a click to make it pass: a retried toggle closes what the first click opened.
Rules¶
CS-E2E-001: Locate elements by test id first¶
Severity: major · Applies to: blazor, template · Enforced by: manual (target: ENF-062) · Status: active
Why¶
A locator built from CSS classes, element nesting, XPath or visible text breaks when a designer changes the markup, when the UI kit changes, or when the page is shown in another language or in right-to-left layout. A data-testid attribute exists only for tests, so it changes only when someone means it to.
Do¶
- Add a
data-testidattribute to every element a test needs, in the.razormarkup, with a stable kebab-case name such asorder-submit. - Locate the element with
GetByTestId("order-submit"). - Use
GetByRolewith an accessible name where the role and name are the thing under test, for example a dialog or a heading. - Scope a locator inside a located parent, for example the row of one order, instead of writing a longer selector.
Don't¶
- Locate by CSS class, by element id or by element structure, such as
Locator(".btn-primary")orLocator("div > table tr:nth-child(2)"). - Locate by XPath or with
text=chains. - Locate by visible text that is translated.
Example¶
<button type="submit" data-testid="order-submit" @onclick="SubmitAsync">@Localizer["Submit"]</button>
// Do
await page.GetByTestId("order-submit").ClickAsync();
// Don't
await page.Locator("form .btn.btn-primary").ClickAsync();
How to check¶
- Search new step code for
Locator("followed by.,#,//,text=or a tag name. - Check that each new
GetByTestIdvalue exists as adata-testidin the.razorfiles. - Search new step code for
GetByText(and check that the text is not a translated UI string.
CS-E2E-002: Never wait for a fixed time¶
Severity: blocker · Applies to: blazor, template · Enforced by: manual (target: ENF-061) · Status: active
Why¶
A fixed wait is either too short under load, so the test fails at random, or too long everywhere, so the suite is slow. It also hides what the test is waiting for. CS-TST-007 bans fixed delays in all tests; this rule is its Playwright form.
Do¶
- Wait for the condition itself: an
Expectassertion,WaitForAsyncon a locator,WaitForResponseAsyncon the request that loads the data, or a poll with a timeout on the service's own record. - Give every wait a timeout and a message that names the condition that never became true.
Don't¶
- Call
page.WaitForTimeoutAsync. - Call
Task.DelayorThread.Sleepin a step or a page object, including inside a loop that walks pages or retries an action.
Example¶
// Do
await Expect(page.GetByTestId("order-status")).ToHaveTextAsync("Submitted");
// Don't
await page.WaitForTimeoutAsync(2000);
Assert.AreEqual("Submitted", await page.GetByTestId("order-status").TextContentAsync());
How to check¶
Search the change for WaitForTimeoutAsync(, Task.Delay( and Thread.Sleep( in end-to-end test projects. Any match is a finding.
CS-E2E-003: Wait for Blazor hydration before you interact¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
A Blazor page is rendered on the server before its circuit connects. Until the client has hydrated the page, a click or a typed value reaches a control that has no handler yet, and it is lost without an error. window.Blazor !== undefined is not the signal: it becomes true as soon as the script has loaded, long before the circuit connects. The failure shows up as a menu that never opens or a form that never submits, mostly under suite load.
Do¶
- After a navigation that starts a new circuit, wait for the circuit's
/_blazorwebsocket, for example withRunAndWaitForWebSocketAsyncaround the navigation. - Then wait until the prerender comment markers are gone: the served page contains comments that start with
Blazor:, and the client removes them while it hydrates. - Then wait for the state your step depends on. Hydration and the component's first data load finish independently, so wait for the list to be populated, not only visible.
- Put the hydration wait in one shared helper that every page object calls.
Don't¶
- Treat
window.Blazorbeing defined, arequestAnimationFrame, orWaitForLoadStateAsync(NetworkIdle)as proof that the page is interactive. - Fill and submit a sign-in form before its circuit is connected.
Example¶
await page.RunAndWaitForWebSocketAsync(
() => page.GotoAsync("/orders"),
new PageRunAndWaitForWebSocketOptions
{
Predicate = socket => socket.Url.Contains("/_blazor", StringComparison.Ordinal),
});
await page.WaitForFunctionAsync(
"""
() => {
if (window.Blazor === undefined) { return false; }
const walker = document.createTreeWalker(document, NodeFilter.SHOW_COMMENT);
while (walker.nextNode()) {
if (walker.currentNode.data.startsWith('Blazor:')) { return false; }
}
return true;
}
""");
await Expect(page.GetByTestId("order-row")).Not.ToHaveCountAsync(0);
How to check¶
- Page objects of Blazor pages call the shared hydration helper after each navigation.
- No step decides that a page is ready from
window.Blazoralone. - No step uses
WaitForLoadStateAsync(NetworkIdle)or arequestAnimationFrameas its readiness signal.
CS-E2E-004: Assert with Expect, not with a one-shot read¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
Expect(...) assertions retry until the condition holds or the timeout ends, so they tolerate a page that is still rendering. IsVisibleAsync(), IsEnabledAsync(), TextContentAsync() and CountAsync() read the page once. An assertion on a one-shot read fails when the page is a moment late, and passes when it is a moment early.
Do¶
- Assert with
Expect(locator).ToBeVisibleAsync(),ToHaveTextAsync,ToHaveCountAsync,ToBeEnabledAsyncand the other Playwright assertions. - Use
Expect(page).ToHaveURLAsyncfor navigation.
Don't¶
- Pass the result of
IsVisibleAsync(),IsEnabledAsync(),TextContentAsync()orCountAsync()toAssert. - Use a one-shot read to decide whether to act. See CS-E2E-005.
Example¶
// Do
await Expect(page.GetByTestId("order-saved")).ToBeVisibleAsync();
// Don't
Assert.IsTrue(await page.GetByTestId("order-saved").IsVisibleAsync());
How to check¶
Search new step code for IsVisibleAsync(), IsEnabledAsync(), TextContentAsync() and CountAsync() whose result goes into an assertion.
CS-E2E-005: Do not check a control and then click it¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
A check followed by a click is two moments. Between them a Blazor circuit can render again: a list settles after a dialog closes, and the Next button becomes disabled with the click already sent. Playwright then waits its whole timeout for a control that will never be enabled. The failure appears only under suite load.
Do¶
- Record the state the click should change, such as the page index shown by the pager.
- Click with a bounded timeout, then wait for that state to change.
- When the only reason a control stops being clickable is that there is nothing more to do, such as the last page, treat a bounded click timeout as that outcome.
- Harden paired steps, such as next page and previous page, in the same way.
Don't¶
- Guard a click with
IsVisibleAsync()andIsEnabledAsync()and assume the result still holds. - Retry a click on a toggle, a menu or any control whose second click undoes the first.
How to check¶
Look for IsEnabledAsync() or IsVisibleAsync() directly before ClickAsync() on the same locator.
CS-E2E-006: Catch action timeouts as TimeoutException¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
A locator action that times out, such as ClickAsync, FillAsync or WaitForAsync, throws System.TimeoutException, which does not derive from PlaywrightException. A retry loop that catches only PlaywrightException around an action never retries. It looks alive in review and fails with Playwright's message instead of the step's own. A failed Expect assertion throws PlaywrightException.
Do¶
- Around an action, catch
Exception ex when (ex is TimeoutException or PlaywrightException). - After the last attempt, throw a message that names the step and the condition.
Don't¶
- Catch only
PlaywrightExceptionaround an action.
Example¶
try
{
await next.ClickAsync(new LocatorClickOptions { Timeout = 5_000 });
}
catch (Exception ex) when (ex is TimeoutException or PlaywrightException)
{
break;
}
How to check¶
Search for catch (PlaywrightException and check whether the try block holds an action rather than an Expect assertion.
CS-E2E-007: Pair every withholding assertion with a positive control¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
An assertion that something is not shown passes when the feature works, and also when the selector never matched anything. Attribute selectors match case-sensitively, and the same identifier often appears as Coordinator on the server and coordinator in the page. A whole feature file can then pass while proving nothing.
Do¶
- For every assertion that content is withheld from one user, add a scenario that asserts the same content is shown to a user who may see it, using the same locator.
- Match identifier and enum attributes case-insensitively with the CSS
iflag, for example[data-customer-id='{id}' i]. - Read the casing from the UI's own constants, not from the service enum.
Don't¶
- Write a scenario whose only assertion is a count of zero.
How to check¶
Each new refusal or hiding scenario has a positive control that uses the same locator.
CS-E2E-008: Settle on evidence the browser did not create¶
Severity: major · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
Some waits succeed whether or not the server received anything. SelectOptionAsync and CheckAsync change the value in the browser, so ToHaveValueAsync right after them is satisfied by the test itself. A wait for a loading indicator to disappear succeeds at once if the indicator has not appeared yet. A step that then navigates away cancels the save it started, and a later step that reads fresh data races the write.
Do¶
- After an action that starts a server write, wait for an effect that only the server can produce: the saved row in the current view, a server-rendered value, or the service's own record read through its API.
- Match that effect by a value unique to this write, such as the title the test generated, so that a row left by an earlier run cannot satisfy it.
- Choose a picker option from the options the picker actually offers, by reading its options, not from a separate API query.
Don't¶
- Assert a control's own value as proof that a change was saved.
- Navigate away, or open the record fresh, before the write's effect is visible.
How to check¶
For each wait after a write, ask: would it still pass if the server never got the request? If yes, it is not a settle.
CS-E2E-009: Pass only supported regex flags to Playwright assertions¶
Severity: minor · Applies to: blazor, template · Enforced by: manual · Status: active
Why¶
Expect sends a .NET Regex to the browser. Only IgnoreCase, Multiline and Singleline are supported. Any other option, such as CultureInvariant, throws before anything is compared. WaitForURLAsync waits for the page's Load event by default, which an in-app Blazor navigation never fires.
Do¶
- Use only
RegexOptions.IgnoreCase,RegexOptions.MultilineandRegexOptions.Singlelinein a regex passed toExpect. - Assert an in-app navigation with
Expect(page).ToHaveURLAsync(...).
Don't¶
- Pass
RegexOptions.CultureInvariantorRegexOptions.CompiledtoExpect. - Wait for an in-app navigation with
WaitForURLAsyncand its default Load wait.
How to check¶
- Search
Expect(calls with aRegexargument for options other than the three supported ones. - Search new step code for
WaitForURLAsync(on an in-app navigation. The step asserts the navigation withExpect(page).ToHaveURLAsync(...)instead.
CS-E2E-010: Keep a screenshot and a trace of every failure¶
Severity: minor · Applies to: blazor, template, pipelines · Enforced by: manual · Status: active
Why¶
An end-to-end failure in CI is hard to reproduce. A screenshot and a Playwright trace show what the page held at the moment of failure, for example a reconnect dialog, an empty menu or a disabled button, and save a rerun.
Do¶
- Start tracing when a test starts, and on failure save the trace and a full-page screenshot under the test results directory.
- Publish that directory as a pipeline artifact.
- Discard the trace of a passing test.
Don't¶
- Rely on the test log alone to diagnose a browser failure.
How to check¶
The test base class or the Reqnroll hooks save a screenshot and a trace on failure, and the pipeline publishes them.
CS-E2E-011: Run one end-to-end lane per environment at a time¶
Severity: major · Applies to: pipelines · Enforced by: manual · Status: active
Why¶
End-to-end suites sign in as the same test users. When an API lane and a browser lane run against one environment at the same time, their sign-ins and multi-factor challenges interfere, and failures look like product defects.
Do¶
- Run the lanes of one environment one after another, for example API, then Chromium, then Firefox.
- Treat a failure from a run that overlapped another run as unproven, and rerun it alone.
Don't¶
- Start a second suite against an environment while one is running.
How to check¶
The pipeline or script that runs the lanes runs them in sequence.