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!

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github