Playwright + TS · Lesson 19 of 36

0/36 done

Module 19: Assertions

19. Web-First Retrying Assertions & Soft Validations

18 minlesson

Try it yourself

Implement formatAssertionError:

  1. Accept field, expected, and actual strings.
  2. Return a formatted error message for test reporting.

The editor has a worked example. Read it, tweak it, then press Mark as complete.

Why Web-First Assertions Eliminate Flakiness

When you call await expect(locator).toBeVisible(), Playwright does not check once and crash. It repeatedly polls the locator until it becomes visible, automatically handling animations and AJAX latency.


Common Web-First Assertions

typescript
// Visibility & State:
await expect(page.getByRole("button", { name: "Submit" })).toBeVisible();
await expect(page.getByRole("button", { name: "Submit" })).toBeEnabled();
await expect(page.getByLabel("Subscribe")).toBeChecked();

// Text & Value:
await expect(page.getByTestId("status-badge")).toHaveText("Active");
await expect(page.getByTestId("welcome-message")).toContainText("Welcome back");
await expect(page.getByLabel("Username")).toHaveValue("john_doe");

// Page & URL:
await expect(page).toHaveURL("https://targetqa.com/dashboard");
await expect(page).toHaveTitle(/TargetQA - Automation Portal/);

// List Count:
await expect(page.locator("ul.cart-items > li")).toHaveCount(3);

Soft Assertions (expect.soft)

Standard expect aborts the test immediately on failure. Soft assertions record the failure and allow the test to continue running to check remaining fields!

typescript
test("validate checkout summary fields", async ({ page }) => {
  await page.goto("/checkout");

  // If subtotal fails, the test continues to verify tax and total!
  await expect.soft(page.getByTestId("subtotal")).toHaveText("$100.00");
  await expect.soft(page.getByTestId("tax")).toHaveText("$10.00");
  await expect.soft(page.getByTestId("total")).toHaveText("$110.00");
});

Key Takeaways & Walkthrough Summary

Flaky tests often happen when assertions run before the page has finished rendering. Playwright solves this with Web-First Assertions: assertions that automatically retry until the condition passes or timeout occurs. In this lesson, we will explore toBeVisible, toHaveText, soft assertions, and URL checks. Let's start asserting!

Part of the Playwright + TS course (Playwright with TypeScript). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why do web-first assertions require the 'await' keyword?

Because they are asynchronous! They poll the browser until the condition passes or timeout occurs. Non-retrying assertions like expect(1+1).toBe(2) do not require await.

What is the default assertion timeout?

5 seconds (5000ms), which can be globally configured in playwright.config.ts under 'expect: { timeout: 5000 }'.

Finished reading?

Review the worked example in the editor, then mark the lesson complete.

TypeScript
Skip