Playwright Assertions
A security guard checks an ID card against a guest list before allowing entry. If the name matches, the guard allows access. If it does not match, the guard denies entry. An assertion works the same way inside a test, comparing what actually appears on a page against what should appear.
How an Assertion Decides
Expected Result vs Actual Result on the Page
\ /
\ /
Comparison Happens
|
+-----+-----+
| |
Match No Match
| |
Pass Fail
Checking Visibility
await expect(page.getByText('Order placed successfully')).toBeVisible();This confirms a success message actually appears on the screen after a customer places an order, catching bugs where a confirmation silently fails to show.
Checking Exact Text
await expect(page.locator('h1')).toHaveText('Welcome Back, Sarah');This checks that a heading shows the exact text "Welcome Back, Sarah," useful for confirming personalized greetings display correctly after login.
Checking Partial Text
await expect(page.locator('.status-message')).toContainText('shipped');This checks that a status message contains the word "shipped" anywhere within it, even if surrounding text like the shipping date changes daily.
Checking Element Count
await expect(page.locator('.cart-item')).toHaveCount(3);This confirms exactly three items sit inside a shopping cart, catching bugs where an item gets added twice by mistake or fails to add at all.
Checking an Input Value
await expect(page.getByLabel('Coupon Code')).toHaveValue('SAVE20');This confirms a coupon field actually holds the typed value, useful after an auto-fill or a page refresh that might clear the field unexpectedly.
Checking an Element Is Disabled
await expect(page.getByRole('button', { name: 'Submit' })).toBeDisabled();This confirms a submit button stays disabled until a form gets filled out completely, a common pattern preventing incomplete submissions.
Why Playwright Assertions Wait Automatically
A page often loads content slightly after the initial page load finishes. Playwright assertions retry checking the condition for a few seconds instead of failing instantly, giving slow-loading elements time to appear naturally.
A Complete Checkout Example
await expect(page.locator('.cart-item')).toHaveCount(2);
await expect(page.locator('.total-price')).toHaveText('$45.99');
await expect(page.getByRole('button', { name: 'Place Order' })).toBeEnabled();These three checks together confirm a shopping cart displays the correct items, calculates the right total, and allows the customer to complete the purchase.
Quick Practice Task
Visit a website with a search feature, run a search, and write an assertion confirming at least one result appears on the screen.
Key Takeaways
- An assertion compares the actual page state to an expected value.
- Playwright assertions retry automatically before reporting a failure.
- Common checks include visibility, text, count, and input values.
- Clear, separate assertions make failures easier to understand later.
