Assertions
Playwright provides convenience APIs for common tasks, like reading the text content of an element. These APIs can be used in your test assertions.
- Text content
- Inner text
- Attribute value
- Checkbox state
- JS expression
- Inner HTML
- Visibility
- Enabled state
- Custom assertions
#
Text contentconst content = await page.textContent('nav:first-child');expect(content).toBe('home');
#
API reference#
Inner textconst text = await page.innerText('.selected');expect(text).toBe('value');
#
API reference#
Attribute valueconst alt = await page.getAttribute('input', 'alt');expect(alt).toBe('Text');
#
Checkbox stateconst checked = await page.isChecked('input');expect(checked).toBeTruthy();
#
API reference#
JS expressionconst content = await page.$eval('nav:first-child', e => e.textContent);expect(content).toBe('home');
#
API reference#
Inner HTMLconst html = await page.innerHTML('div.result');expect(html).toBe('<p>Result</p>');
#
API reference#
Visibilityconst visible = await page.isVisible('input');expect(visible).toBeTruthy();
#
API reference#
Enabled stateconst enabled = await page.isEnabled('input');expect(enabled).toBeTruthy();
#
API reference#
Custom assertionsWith Playwright, you can also write custom JavaScript to run in the context of the browser. This is useful in situations where you want to assert for values that are not covered by the convenience APIs above.
// Assert local storage valueconst userId = page.evaluate(() => window.localStorage.getItem('userId'));expect(userId).toBeTruthy();
// Assert value for input elementawait page.waitForSelector('#search');const value = await page.inputValue('#search');expect(value === 'query').toBeTruthy();
// Assert computed styleconst fontSize = await page.$eval('div', el => window.getComputedStyle(el).fontSize);expect(fontSize === '16px').toBeTruthy();
// Assert list lengthconst length = await page.$$eval('li.selected', (items) => items.length);expect(length === 3).toBeTruthy();
#
API reference- page.evaluate(pageFunction[, arg])
- page.$eval(selector, pageFunction[, arg, options])
- page.$$eval(selector, pageFunction[, arg])
- frame.evaluate(pageFunction[, arg])
- frame.$eval(selector, pageFunction[, arg, options])
- frame.$$eval(selector, pageFunction[, arg])
- elementHandle.$eval(selector, pageFunction[, arg])
- elementHandle.$$eval(selector, pageFunction[, arg])
- EvaluationArgument