Assertions (expect)
Relevant source files
The following files were used as context for generating this wiki page:
Playwright Test includes a powerful and flexible assertion library, accessed through the expect function. This library is designed to be deeply integrated with the test runner, providing features like auto-waiting, retries for web-first assertions, and detailed, readable error messages. It supports a wide range of assertions, from generic value checks to specialized, async assertions for web pages, locators, and API responses.
The assertion library is extensible, allowing for the creation of custom matchers to suit project-specific needs. It also offers "soft" assertions, which record failures without immediately terminating the test, enabling more comprehensive error reporting in a single test run. Configuration can be managed globally, per-project, or even per-test, offering fine-grained control over assertion behavior like timeouts.
Sources: packages/playwright/types/test.d.ts:3148-3158, tests/playwright-test/expect-soft.spec.ts
Configuration
The behavior of expect assertions can be customized within the playwright.config.ts file, either at the top level or on a per-project basis. This allows for setting default timeouts and configuring snapshot matching behavior.
| Option | Type | Description |
|---|---|---|
timeout | number | Default timeout for async expect matchers in milliseconds. Defaults to 5000ms. |
toHaveScreenshot | object | Configuration for expect(page).toHaveScreenshot(), including threshold, maxDiffPixels, animations, caret, scale, and stylePath. |
toMatchSnapshot | object | Configuration for expect(value).toMatchSnapshot(), including threshold, maxDiffPixels, and maxDiffPixelRatio. |
toPass | object | Configuration for expect().toPass(), including timeout and intervals. |
Sources: packages/playwright/types/test.d.ts:187-268, packages/playwright/types/test.d.ts:1003-1084
Configuration Example
Here is an example of how to configure the expect timeout in playwright.config.js:
// playwright.config.js
module.exports = {
expect: {
timeout: 1000
}
}
This configuration sets the default timeout for all async assertions to 1000 milliseconds.
Sources: tests/playwright-test/expect.spec.ts:269-271
Core API
The expect API provides several functions to create different types of assertions.
expect(actual, message?)
This is the standard assertion. It takes an actual value and an optional custom error message. If the assertion fails, the test is terminated immediately.
// tests/playwright-test/expect.spec.ts:29-31
test('custom expect message', () => {
test.expect(1+1, 'one plus one should be two!').toEqual(3);
});
Sources: tests/playwright-test/expect.spec.ts:28-38
expect.soft(actual, message?)
Soft assertions do not immediately terminate the test. Instead, they record the failure and allow the test to continue. All soft assertion failures are reported at the end of the test.
The following diagram illustrates the execution flow difference between a standard and a soft assertion.
expect.poll(callback, options?)
This function is used for making assertions on values that change over time. It repeatedly executes the provided callback function until the chained assertions pass or a timeout is reached.
callback: A function that returns a value or aPromisefor a value to be asserted.options.timeout: The maximum time to wait.options.intervals: The polling intervals.
Sources: packages/playwright/types/test.d.ts:3423-3437
expect.extend(matchers)
The expect object can be extended with custom matchers. This is useful for creating domain-specific assertions that make tests more readable and maintainable.
Sources: packages/playwright/types/test.d.ts:3438-3441, tests/playwright-test/expect.spec.ts:384-436
Assertion Types
Playwright's expect provides different sets of matchers depending on the type of the object being asserted.
Generic Assertions
These can be used on any type of value.
| Matcher | Description |
|---|---|
.toBe(expected) | Checks for strict equality (Object.is). |
.toEqual(expected) | Performs a deep equality check for objects and arrays. |
.toBeTruthy() | Asserts that the value is not false, 0, '', null, undefined, or NaN. |
.toBeFalsy() | Asserts that the value is false, 0, '', null, undefined, or NaN. |
.toContain(item) | Checks if an array or string contains an item or substring. |
.toHaveLength(number) | Checks that an object has a .length property and it is equal to the given number. |
.toThrow(error) | Checks that a function throws an error when called. |
Sources: packages/playwright/types/test.d.ts:3335-3402
Locator and Page Assertions (Web-First)
These assertions are designed for web testing and include auto-waiting and retrying logic. They are available on Locator and Page objects.
The following diagram shows the async, retrying nature of a web-first assertion.
Common Locator Assertions:
| Matcher | Description |
|---|---|
.toBeVisible() | Ensures the locator points to a visible element. |
.toBeHidden() | Ensures the locator points to a hidden or non-existent element. |
.toBeEnabled() | Ensures the locator points to an enabled element. |
.toBeEditable() | Ensures the locator points to an editable element. |
.toHaveText(text) | Ensures the element has the specified text content. |
.toHaveAttribute(name, value) | Ensures the element has the specified attribute. |
.toHaveCount(count) | Ensures the locator resolves to a specific number of elements. |
.toHaveScreenshot(name) | Compares the element's screenshot with a stored snapshot. |
Sources: packages/playwright/types/test.d.ts:3533-3921
Common Page Assertions:
| Matcher | Description |
|---|---|
.toHaveURL(url) | Ensures the page is at the specified URL. |
.toHaveTitle(title) | Ensures the page has the specified title. |
.toHaveScreenshot(name) | Compares the page's screenshot with a stored snapshot. |
Sources: packages/playwright/types/test.d.ts:3923-4001
APIResponse Assertions
These assertions are for validating responses from API requests made with request.
| Matcher | Description |
|---|---|
.toBeOK() | Ensures the response status code is in the 2xx range. |
Sources: packages/playwright/types/test.d.ts:3514-3531
Snapshot Assertions
These assertions compare a value (string, buffer, or screenshot) against a stored baseline "snapshot" file.
| Matcher | Description |
|---|---|
.toMatchSnapshot(name) | Compares a string or buffer with a text or binary snapshot. |
.toHaveScreenshot(name) | A specialized snapshot assertion for Locator and Page that compares screenshots. It waits for the element to be stable before taking the screenshot. |
Snapshots are a powerful tool for testing complex data structures, rendered UI, and images. They are stored in a *-snapshots directory next to the test file.
Sources: packages/playwright/types/test.d.ts:4003-4100, tests/playwright-test/golden.spec.ts
Extensibility: Custom Matchers
Playwright's expect can be extended with custom matchers to create domain-specific assertions. This is done using expect.extend(). A custom matcher is a function that receives the actual value and any expected arguments. It must return an object indicating whether the assertion passed and a message function to generate the error message on failure.
The following diagram shows the structure of a custom matcher's return value and its state object.
This diagram shows the ExpectMatcherState provided to custom matchers, which includes utilities for creating rich error messages, and the MatcherReturnType object that matchers must return.
Sources: packages/playwright/types/test.d.ts:3442-3472
Example of a Custom Matcher
This example from the Playwright test suite shows how to create a custom matcher toHaveAmount.
// From tests/playwright-test/expect.spec.ts
const expect = baseExpect.extend({
async toHaveAmount(locator: Locator, expected: string, options?: { timeout?: number }) {
const baseAmount = locator.locator('.base-amount');
let pass: boolean;
let matcherResult: any;
try {
const expectation = this.isNot ? baseExpect(baseAmount).not : baseExpect(baseAmount);
await expectation.toHaveAttribute('data-amount', expected, options);
pass = true;
} catch (e: any) {
matcherResult = e.matcherResult;
pass = false;
}
if (this.isNot) {
pass = !pass;
}
// ... message generation using this.utils ...
return {
name: 'toHaveAmount',
expected,
message,
pass,
actual: matcherResult?.actual,
log: matcherResult?.log,
};
},
});
Sources: tests/playwright-test/expect.spec.ts:386-435
Summary
The expect assertion library is a cornerstone of testing in Playwright. It provides a rich, fluent, and extensible API for writing powerful and readable tests. Its deep integration with the test runner, featuring auto-waiting for web-first assertions, detailed error reporting, and configurable behavior, makes it an essential tool for robust end-to-end and component testing. The ability to use soft assertions and create custom matchers further enhances its flexibility, allowing it to be tailored to any project's specific validation needs.