How to Check an Element's Value in Playwright

Better Stack Team
Updated on February 22, 2024

🔭 Want to automate and scale your Playwright end-to-end tests?

Head over to Better Stack and start monitoring in 5 minutes.

With the release of Playwright version 1.20, the framework introduced the toHaveValue() assertion, enhancing the process of verifying the value held by elements such as input fields:

 
await expect(page.locator('input#name-input')).toHaveValue('John Doe');

This assertion also supports the use of regular expressions for more dynamic checks:

 
await expect(page.locator('input#name-input')).toHaveValue(/\w+/);

When dealing with select elements that permit multiple selections, the toHaveValues() assertion comes into play, allowing verification against multiple expected values:

 
await expect(page.locator('select')).toHaveValues([/Red/, /Green/]);

If your intention is merely to retrieve an element's value without making an assertion, the inputValue() method is applicable for <input>, <textarea>, and <select> elements:

 
const value = page.locator('input#name-input').inputValue();

For retrieving text from other element types, innerText() is the method of choice, while toHaveText() serves to assert the text content:

 
const value = await page.getByRole('heading').innerText();
 
await expect(page.getByRole('heading')).toHaveText('A heading');

Thanks for reading, and happy coding!