How do I return the value of elem so that I can verify that it is in fact 1
?
const elem = await page.$('input#my-input')
await elem.fill('1')
How do I return the value of elem so that I can verify that it is in fact 1
?
const elem = await page.$('input#my-input')
await elem.fill('1')
Also, since v1.20 there's the toHaveValue
matcher that can verify an element's value:
await expect(page.locator('input#my-input')).toHaveValue('1');
inputValue
method has been added in Playwright v1.13.0
await page.inputValue('input#my-input');
Locator:
await page.locator('input#my-input').inputValue();
It returns input.value
for the selected <input>
or <textarea>
element. Throws for non-input elements. Read more.
Meanwhile, if you want to assert the value you can use toHaveValue
const locator = page.locator('input#my-input');
await expect(locator).toHaveValue(/[0-9]/);
The easiest way is to use $eval
. Here you see a small example:
const playwright = require("playwright");
(async () => {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.setContent(`<input id="foo"/>`);
await page.type("#foo", "New value")
console.log(await page.$eval("#foo", el => el.value))
await page.screenshot({ path: `example.png` });
await browser.close();
})();
From version 1.19 (and probably lower versions) Element Handler is not recomended. Instead of it use Locator.
page.locator(selector).innerText()
in your case with assertion it will be
expect(page.locator("input#my-input").innerText().includes("1")).toBeTruthy()
Read more on: https://playwright.dev/docs/api/class-elementhandle#element-handle-fill
How to verify value from textbox?
In latest playwright version, toHaveValue combines getting and verifying input value in single step.
const locator = page.locator('input[type=number]');
await expect(locator).toHaveValue('1');
It ensures the Locator points to an element with the given input value. You can use regular expressions for the value as well.
Reference: https://playwright.dev/docs/api/class-locatorassertions#locator-assertions-to-have-value
This is to get the value through chrome context ( like executing in chrome devtools console )
.
.
As per the latest document it can be achieved using page.evaluate
.
https://playwright.dev/docs/evaluating
.
.
const linkhrefFromBrowser = await page.evaluate(async () => {
// The below instructions will run in the browser console ( context )
let element = element.getElementById("pagelink");
let linkhref = element.getAttribute("href");
console.log(linkhref); // will be printed in browser tab
return linkhref; // whatever you return will be available in linkhrefFromBrowser variable
});