0
# Assertions
1
2
Web-specific assertion library with automatic waiting and retry logic for reliable test assertions. Provides comprehensive matchers for page elements, network requests, and application state.
3
4
## Capabilities
5
6
### Core Expect Function
7
8
Main assertion function with support for various assertion modes and configuration options.
9
10
```typescript { .api }
11
/**
12
* Create assertions for any value with automatic retry logic
13
* @param actual - Value to assert against
14
* @returns Assertion object with matcher methods
15
*/
16
function expect<T>(actual: T): PlaywrightAssertions<T>;
17
18
/**
19
* Create soft assertions that don't immediately fail the test
20
* @param actual - Value to assert against
21
* @returns Soft assertion object that collects failures
22
*/
23
expect.soft<T>(actual: T): PlaywrightAssertions<T>;
24
25
/**
26
* Create polling assertions that retry until condition is met
27
* @param actual - Function returning value to assert against
28
* @param options - Polling configuration
29
* @returns Polling assertion object
30
*/
31
expect.poll<T>(
32
actual: () => T | Promise<T>,
33
options?: { intervals?: number[]; timeout?: number }
34
): PlaywrightAssertions<T>;
35
36
/**
37
* Add custom matcher methods to expect
38
* @param matchers - Object with custom matcher implementations
39
*/
40
expect.extend<T>(matchers: CustomMatchers<T>): void;
41
42
/**
43
* Configure global expect behavior
44
* @param options - Global expect configuration
45
*/
46
expect.configure(options: {
47
timeout?: number;
48
soft?: boolean;
49
}): void;
50
```
51
52
**Usage Examples:**
53
54
```typescript
55
import { test, expect } from "@playwright/test";
56
57
test("basic assertions", async ({ page }) => {
58
await page.goto("/");
59
60
// Standard assertions
61
await expect(page.locator("h1")).toBeVisible();
62
await expect(page).toHaveTitle("Home Page");
63
64
// Soft assertions (collect errors, don't fail immediately)
65
await expect.soft(page.locator(".warning")).toBeHidden();
66
await expect.soft(page.locator(".error")).toHaveCount(0);
67
68
// Polling assertions (retry until condition met)
69
await expect.poll(async () => {
70
const response = await page.request.get("/api/status");
71
return response.status();
72
}).toBe(200);
73
});
74
75
// Configure global timeout
76
expect.configure({ timeout: 10000 });
77
```
78
79
### Page Assertions
80
81
Assertions specifically designed for page-level properties and states.
82
83
```typescript { .api }
84
/**
85
* Assert page has specific title
86
* @param expected - Expected title (string or regex)
87
* @param options - Assertion options
88
*/
89
toHaveTitle(expected: string | RegExp, options?: { timeout?: number }): Promise<void>;
90
91
/**
92
* Assert page URL matches pattern
93
* @param expected - Expected URL (string or regex)
94
* @param options - Assertion options
95
*/
96
toHaveURL(expected: string | RegExp, options?: { timeout?: number }): Promise<void>;
97
98
/**
99
* Assert page screenshot matches expected image
100
* @param name - Screenshot name for comparison
101
* @param options - Screenshot comparison options
102
*/
103
toHaveScreenshot(name?: string | string[], options?: {
104
threshold?: number;
105
maxDiffPixels?: number;
106
animations?: 'disabled' | 'allow';
107
caret?: 'hide' | 'initial';
108
scale?: 'css' | 'device';
109
mode?: 'light' | 'dark';
110
}): Promise<void>;
111
```
112
113
**Usage Examples:**
114
115
```typescript
116
test("page assertions", async ({ page }) => {
117
await page.goto("/dashboard");
118
119
// Title and URL assertions
120
await expect(page).toHaveTitle("User Dashboard");
121
await expect(page).toHaveTitle(/Dashboard/);
122
await expect(page).toHaveURL("/dashboard");
123
await expect(page).toHaveURL(/\/dashboard/);
124
125
// Visual regression testing
126
await expect(page).toHaveScreenshot("dashboard.png");
127
await expect(page).toHaveScreenshot("dashboard.png", {
128
threshold: 0.2,
129
maxDiffPixels: 100
130
});
131
});
132
```
133
134
### Element Assertions
135
136
Comprehensive assertions for element visibility, content, attributes, and states.
137
138
```typescript { .api }
139
/**
140
* Assert element is visible on page
141
* @param options - Assertion options
142
*/
143
toBeVisible(options?: { timeout?: number }): Promise<void>;
144
145
/**
146
* Assert element is hidden from view
147
* @param options - Assertion options
148
*/
149
toBeHidden(options?: { timeout?: number }): Promise<void>;
150
151
/**
152
* Assert element is enabled for interaction
153
* @param options - Assertion options
154
*/
155
toBeEnabled(options?: { timeout?: number }): Promise<void>;
156
157
/**
158
* Assert element is disabled
159
* @param options - Assertion options
160
*/
161
toBeDisabled(options?: { timeout?: number }): Promise<void>;
162
163
/**
164
* Assert element is editable (input/textarea)
165
* @param options - Assertion options
166
*/
167
toBeEditable(options?: { timeout?: number }): Promise<void>;
168
169
/**
170
* Assert checkbox/radio is checked
171
* @param options - Assertion options
172
*/
173
toBeChecked(options?: { timeout?: number }): Promise<void>;
174
175
/**
176
* Assert element is focused
177
* @param options - Assertion options
178
*/
179
toBeFocused(options?: { timeout?: number }): Promise<void>;
180
181
/**
182
* Assert element contains specific text
183
* @param expected - Expected text (string or regex)
184
* @param options - Assertion options
185
*/
186
toContainText(expected: string | RegExp | (string | RegExp)[], options?: {
187
ignoreCase?: boolean;
188
timeout?: number;
189
useInnerText?: boolean;
190
}): Promise<void>;
191
192
/**
193
* Assert element has exact text content
194
* @param expected - Expected text (string or regex)
195
* @param options - Assertion options
196
*/
197
toHaveText(expected: string | RegExp | (string | RegExp)[], options?: {
198
ignoreCase?: boolean;
199
timeout?: number;
200
useInnerText?: boolean;
201
}): Promise<void>;
202
203
/**
204
* Assert element has specific attribute value
205
* @param name - Attribute name
206
* @param value - Expected value (string or regex)
207
* @param options - Assertion options
208
*/
209
toHaveAttribute(name: string, value?: string | RegExp, options?: { timeout?: number }): Promise<void>;
210
211
/**
212
* Assert input element has specific value
213
* @param value - Expected value (string or regex)
214
* @param options - Assertion options
215
*/
216
toHaveValue(value: string | RegExp, options?: { timeout?: number }): Promise<void>;
217
218
/**
219
* Assert element has specific CSS property value
220
* @param name - CSS property name
221
* @param value - Expected value (string or regex)
222
* @param options - Assertion options
223
*/
224
toHaveCSS(name: string, value: string | RegExp, options?: { timeout?: number }): Promise<void>;
225
226
/**
227
* Assert element has specific class
228
* @param expected - Expected class names
229
* @param options - Assertion options
230
*/
231
toHaveClass(expected: string | RegExp | (string | RegExp)[], options?: { timeout?: number }): Promise<void>;
232
233
/**
234
* Assert number of matching elements
235
* @param count - Expected count
236
* @param options - Assertion options
237
*/
238
toHaveCount(count: number, options?: { timeout?: number }): Promise<void>;
239
240
/**
241
* Assert element screenshot matches expected
242
* @param name - Screenshot name for comparison
243
* @param options - Screenshot comparison options
244
*/
245
toHaveScreenshot(name?: string | string[], options?: ScreenshotOptions): Promise<void>;
246
```
247
248
**Usage Examples:**
249
250
```typescript
251
test("element assertions", async ({ page }) => {
252
await page.goto("/form");
253
254
// Visibility and state assertions
255
await expect(page.locator(".loading")).toBeHidden();
256
await expect(page.locator("#submit-btn")).toBeVisible();
257
await expect(page.locator("#submit-btn")).toBeEnabled();
258
await expect(page.locator("#terms")).toBeChecked();
259
260
// Content assertions
261
await expect(page.locator("h1")).toHaveText("Contact Form");
262
await expect(page.locator(".error")).toContainText("required");
263
await expect(page.locator("input#email")).toHaveValue("user@example.com");
264
265
// Attribute and CSS assertions
266
await expect(page.locator("button")).toHaveAttribute("type", "submit");
267
await expect(page.locator(".highlight")).toHaveCSS("background-color", "rgb(255, 255, 0)");
268
await expect(page.locator(".active")).toHaveClass("tab active");
269
270
// Count assertions
271
await expect(page.locator(".menu-item")).toHaveCount(5);
272
await expect(page.locator(".error")).toHaveCount(0);
273
});
274
```
275
276
### Value and Content Assertions
277
278
Standard assertions for primitive values, objects, and arrays.
279
280
```typescript { .api }
281
/**
282
* Assert values are strictly equal
283
* @param expected - Expected value
284
*/
285
toBe(expected: any): Promise<void>;
286
287
/**
288
* Assert values are deeply equal
289
* @param expected - Expected value
290
*/
291
toEqual(expected: any): Promise<void>;
292
293
/**
294
* Assert value is strictly equal to expected
295
* @param expected - Expected value
296
*/
297
toStrictEqual(expected: any): Promise<void>;
298
299
/**
300
* Assert value is truthy
301
*/
302
toBeTruthy(): Promise<void>;
303
304
/**
305
* Assert value is falsy
306
*/
307
toBeFalsy(): Promise<void>;
308
309
/**
310
* Assert value is defined (not undefined)
311
*/
312
toBeDefined(): Promise<void>;
313
314
/**
315
* Assert value is undefined
316
*/
317
toBeUndefined(): Promise<void>;
318
319
/**
320
* Assert value is null
321
*/
322
toBeNull(): Promise<void>;
323
324
/**
325
* Assert value is NaN
326
*/
327
toBeNaN(): Promise<void>;
328
329
/**
330
* Assert array/string contains specific item/substring
331
* @param expected - Expected item or substring
332
*/
333
toContain(expected: any): Promise<void>;
334
335
/**
336
* Assert object has specific property
337
* @param keyPath - Property key or path (dot notation)
338
* @param value - Optional expected value
339
*/
340
toHaveProperty(keyPath: string | string[], value?: any): Promise<void>;
341
342
/**
343
* Assert number is greater than expected
344
* @param expected - Expected minimum value
345
*/
346
toBeGreaterThan(expected: number): Promise<void>;
347
348
/**
349
* Assert number is greater than or equal to expected
350
* @param expected - Expected minimum value
351
*/
352
toBeGreaterThanOrEqual(expected: number): Promise<void>;
353
354
/**
355
* Assert number is less than expected
356
* @param expected - Expected maximum value
357
*/
358
toBeLessThan(expected: number): Promise<void>;
359
360
/**
361
* Assert number is less than or equal to expected
362
* @param expected - Expected maximum value
363
*/
364
toBeLessThanOrEqual(expected: number): Promise<void>;
365
366
/**
367
* Assert number is close to expected within precision
368
* @param expected - Expected value
369
* @param precision - Decimal precision (default: 2)
370
*/
371
toBeCloseTo(expected: number, precision?: number): Promise<void>;
372
373
/**
374
* Assert string matches regular expression
375
* @param expected - Regular expression pattern
376
*/
377
toMatch(expected: RegExp | string): Promise<void>;
378
379
/**
380
* Assert function throws error
381
* @param expected - Expected error (optional)
382
*/
383
toThrow(expected?: string | RegExp | Error): Promise<void>;
384
385
/**
386
* Assert array has specific length
387
* @param expected - Expected length
388
*/
389
toHaveLength(expected: number): Promise<void>;
390
```
391
392
**Usage Examples:**
393
394
```typescript
395
test("value assertions", async ({ page }) => {
396
const result = await page.evaluate(() => {
397
return {
398
count: 42,
399
name: "test",
400
items: ["a", "b", "c"],
401
active: true
402
};
403
});
404
405
// Equality assertions
406
expect(result.count).toBe(42);
407
expect(result).toEqual({ count: 42, name: "test", items: ["a", "b", "c"], active: true });
408
409
// Property assertions
410
expect(result).toHaveProperty("name", "test");
411
expect(result).toHaveProperty("items.length", 3);
412
413
// Number assertions
414
expect(result.count).toBeGreaterThan(40);
415
expect(result.count).toBeLessThanOrEqual(50);
416
417
// Array assertions
418
expect(result.items).toContain("b");
419
expect(result.items).toHaveLength(3);
420
421
// Boolean assertions
422
expect(result.active).toBeTruthy();
423
expect(result.disabled).toBeFalsy();
424
});
425
```
426
427
### Network Assertions
428
429
Assertions for API requests and responses.
430
431
```typescript { .api }
432
/**
433
* Assert API response has expected status
434
* @param expected - Expected status code
435
*/
436
toBeOK(): Promise<void>;
437
438
/**
439
* Assert response status matches expected
440
* @param expected - Expected status code
441
*/
442
toHaveStatus(expected: number): Promise<void>;
443
444
/**
445
* Assert response has specific header
446
* @param name - Header name
447
* @param value - Expected header value (optional)
448
*/
449
toHaveHeader(name: string, value?: string | RegExp): Promise<void>;
450
451
/**
452
* Assert response body matches expected
453
* @param expected - Expected response body
454
*/
455
toHaveBody(expected: string | Buffer | RegExp): Promise<void>;
456
457
/**
458
* Assert response JSON matches expected
459
* @param expected - Expected JSON object
460
*/
461
toHaveJSON(expected: object): Promise<void>;
462
```
463
464
**Usage Examples:**
465
466
```typescript
467
test("API assertions", async ({ request }) => {
468
const response = await request.get("/api/users");
469
470
// Status assertions
471
await expect(response).toBeOK();
472
await expect(response).toHaveStatus(200);
473
474
// Header assertions
475
await expect(response).toHaveHeader("content-type", /application\/json/);
476
477
// Body assertions
478
const userData = await response.json();
479
expect(userData).toHaveProperty("users");
480
expect(userData.users).toHaveLength(10);
481
});
482
```
483
484
## Custom Matchers
485
486
### Extending Expect
487
488
```typescript { .api }
489
interface CustomMatchers<R = unknown> {
490
[matcher: string]: (this: MatcherState, received: any, ...args: any[]) => CustomMatcherResult | Promise<CustomMatcherResult>;
491
}
492
493
interface CustomMatcherResult {
494
pass: boolean;
495
message: () => string;
496
actual?: any;
497
expected?: any;
498
}
499
500
interface MatcherState {
501
equals: (a: any, b: any) => boolean;
502
expand?: boolean;
503
isNot: boolean;
504
promise: string;
505
suppressedErrors: Error[];
506
utils: MatcherUtils;
507
}
508
```
509
510
**Usage Examples:**
511
512
```typescript
513
// Define custom matcher
514
expect.extend({
515
async toHaveValidationError(locator: Locator, expectedMessage: string) {
516
const errorElement = locator.locator(".error-message");
517
const isVisible = await errorElement.isVisible();
518
const actualMessage = isVisible ? await errorElement.textContent() : null;
519
520
const pass = isVisible && actualMessage === expectedMessage;
521
522
return {
523
pass,
524
message: () => pass
525
? `Expected validation error "${expectedMessage}" not to be present`
526
: `Expected validation error "${expectedMessage}", but got "${actualMessage}"`
527
};
528
}
529
});
530
531
// Use custom matcher
532
test("custom assertion", async ({ page }) => {
533
await page.goto("/form");
534
await page.click("#submit");
535
536
await expect(page.locator("#email-field")).toHaveValidationError("Email is required");
537
});
538
```
539
540
## Core Types
541
542
### Assertion Interfaces
543
544
```typescript { .api }
545
interface PlaywrightAssertions<T> {
546
not: PlaywrightAssertions<T>;
547
548
// Value assertions
549
toBe(expected: any): Promise<void>;
550
toEqual(expected: any): Promise<void>;
551
toStrictEqual(expected: any): Promise<void>;
552
toBeTruthy(): Promise<void>;
553
toBeFalsy(): Promise<void>;
554
toBeDefined(): Promise<void>;
555
toBeUndefined(): Promise<void>;
556
toBeNull(): Promise<void>;
557
toBeNaN(): Promise<void>;
558
toContain(expected: any): Promise<void>;
559
toHaveProperty(keyPath: string | string[], value?: any): Promise<void>;
560
toHaveLength(expected: number): Promise<void>;
561
toMatch(expected: RegExp | string): Promise<void>;
562
toThrow(expected?: string | RegExp | Error): Promise<void>;
563
564
// Number assertions
565
toBeGreaterThan(expected: number): Promise<void>;
566
toBeGreaterThanOrEqual(expected: number): Promise<void>;
567
toBeLessThan(expected: number): Promise<void>;
568
toBeLessThanOrEqual(expected: number): Promise<void>;
569
toBeCloseTo(expected: number, precision?: number): Promise<void>;
570
571
// Element assertions (when T is Locator)
572
toBeVisible?(options?: { timeout?: number }): Promise<void>;
573
toBeHidden?(options?: { timeout?: number }): Promise<void>;
574
toBeEnabled?(options?: { timeout?: number }): Promise<void>;
575
toBeDisabled?(options?: { timeout?: number }): Promise<void>;
576
toBeEditable?(options?: { timeout?: number }): Promise<void>;
577
toBeChecked?(options?: { timeout?: number }): Promise<void>;
578
toBeFocused?(options?: { timeout?: number }): Promise<void>;
579
toContainText?(expected: string | RegExp | (string | RegExp)[], options?: TextOptions): Promise<void>;
580
toHaveText?(expected: string | RegExp | (string | RegExp)[], options?: TextOptions): Promise<void>;
581
toHaveAttribute?(name: string, value?: string | RegExp, options?: { timeout?: number }): Promise<void>;
582
toHaveValue?(value: string | RegExp, options?: { timeout?: number }): Promise<void>;
583
toHaveCSS?(name: string, value: string | RegExp, options?: { timeout?: number }): Promise<void>;
584
toHaveClass?(expected: string | RegExp | (string | RegExp)[], options?: { timeout?: number }): Promise<void>;
585
toHaveCount?(count: number, options?: { timeout?: number }): Promise<void>;
586
toHaveScreenshot?(name?: string | string[], options?: ScreenshotOptions): Promise<void>;
587
588
// Page assertions (when T is Page)
589
toHaveTitle?(expected: string | RegExp, options?: { timeout?: number }): Promise<void>;
590
toHaveURL?(expected: string | RegExp, options?: { timeout?: number }): Promise<void>;
591
592
// Response assertions (when T is APIResponse)
593
toBeOK?(): Promise<void>;
594
toHaveStatus?(expected: number): Promise<void>;
595
toHaveHeader?(name: string, value?: string | RegExp): Promise<void>;
596
toHaveBody?(expected: string | Buffer | RegExp): Promise<void>;
597
toHaveJSON?(expected: object): Promise<void>;
598
}
599
600
interface TextOptions {
601
ignoreCase?: boolean;
602
timeout?: number;
603
useInnerText?: boolean;
604
}
605
606
interface ScreenshotOptions {
607
threshold?: number;
608
maxDiffPixels?: number;
609
animations?: 'disabled' | 'allow';
610
caret?: 'hide' | 'initial';
611
scale?: 'css' | 'device';
612
mode?: 'light' | 'dark';
613
timeout?: number;
614
}
615
```