Playwright + TS · Lesson 19 of 36
Module 19: Assertions
Try it yourself
Implement formatAssertionError:
The editor has a worked example. Read it, tweak it, then press Mark as complete.
In this lesson
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.
// 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);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!
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");
});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.
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.
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.