Assertions

The Playwright API can be used to read element contents and properties for test assertions. These values are fetched from the browser page and asserted in Node.js.

The examples in this guide use the built-in assert module, but they can be used with any assertion library (like Expect or Chai). See Test runners for more info.

Common patterns

Playwright provides convenience APIs for common assertion tasks, like finding the text content of an element. These APIs require a selector to locate the element.

  1. // Assert text content
  2. const content = await page.textContent('nav:first-child');
  3. assert(content === 'home');
  4. // Assert inner text
  5. const text = await page.innerText('.selected');
  6. assert(text === 'value');
  7. // Assert inner HTML
  8. const html = await page.innerHTML('div.result');
  9. assert(html === '<p>Result</p>')
  10. // Assert `checked` attribute
  11. const checked = await page.getAttribute('input', 'checked');
  12. assert(checked);

API reference

Element Handles

ElementHandle objects represent in-page DOM elements. They can be used to assert for multiple properties of the element.

It is recommended to fetch the ElementHandle object with page.waitForSelector or frame.waitForSelector. These APIs wait for the element to be visible and then return an ElementHandle.

  1. // Get the element handle
  2. const elementHandle = page.waitForSelector('#box');
  3. // Assert bounding box for the element
  4. const boundingBox = await elementHandle.boundingBox();
  5. assert(boundingBox.width === 100);
  6. // Assert attribute for the element
  7. const classNames = await elementHandle.getAttribute('class');
  8. assert(classNames.includes('highlighted'));

API reference

Custom assertions

With 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.

The following APIs do not auto-wait for the element. It is recommended to use page.waitForSelector or frame.waitForSelector.

  1. // Assert local storage value
  2. const userId = page.evaluate(() => window.localStorage.getItem('userId'));
  3. assert(userId);
  4. // Assert value for input element
  5. await page.waitForSelector('#search');
  6. const value = await page.$eval('#search', el => el.value);
  7. assert(value === 'query');
  8. // Assert computed style
  9. const fontSize = await page.$eval('div', el => window.getComputedStyle(el).fontSize);
  10. assert(fontSize === '16px');
  11. // Assert list length
  12. const length = await page.$$eval('li.selected', (items) => items.length);
  13. assert(length === 3);

API reference