I am wondering if someone could give an idea how to access and change the content of value attribute in the code below.
<table>
<thead>
<tr>...</tr>
</thead>
<tbody>
<tr>...</tr>
<tr>
<td>Test</td>
<td><input type="text" id="id_1" name="test_name_1" value="John"></td>
<td><input type="text" id="id_2" name="test_n_2" value="Student"></td>
</tr>
</tbody>
</table>
Verified with: expect(await page.locator('td:has-text("John")')).toBeTruthy();
How do I change the value in td -> input, that is, value="John" => value="Paul"
and value="Student" => value="Teacher"
?
For starters, your assertion is broken--it always passes because it's testing whether Playwright locator objects are truthy (page.locator()
doesn't return a promise, so awaiting it doesn't do anything). Always make your tests fail (for example, by removing the element from the page), then make them pass (by re-adding the element), to ensure that there's no false positives and the test is testing what you think it is. Also, generally use web first assertions, which would help avoid this sort of mistake.
toBeTruthy()
is generally too broad for most assertions. It'd be better to use toHaveValue()
since that's precisely the condition you want to test, so it better communicates your intent and makes the failure error message more comprehensible. This also helps avoid false positives.
import {expect, test} from "@playwright/test"; // ^1.39.0
const html = `::the HTML from your post::`;
test('has a name="test_name_1" input with value "John"', async ({page}) => {
await page.setContent(html);
await expect(page.locator('td input[name="test_name_1"]')).toHaveValue("John");
});
To fill it, you can use .fill()
:
test('can change value of name="test_name_1" input', async ({page}) => {
await page.setContent(html);
const input = page.locator('td input[name="test_name_1"]');
await input.fill("whatever");
await expect(input).toHaveValue("whatever");
});