Search code examples
typescriptplaywrightplaywright-typescript

Selecting text and storing it in a variable for later use in PlayWright


I have a playwright test which logs into my system as a privileged user, and creates a new user. I was hoping that I could then copy the username and password (which is displayed in a html table with fields with indiviual IDs for each cell). I thought this code worked:

// copy username and password
const username = await page.locator('#username0').selectText();
const password = await page.locator('#passwd0').selectText();
const screenshot4 = await page.locator('#CreatedUsers').screenshot();
await testInfo.attach('admin_002-usercReated_selectedPW0', { body: screenshot4, contentType: 'image/png' });
expect(username).not.toBeNull();
expect(password).not.toBeNull();

until I added these assertions:

expect(username).not.toBeUndefined();
expect(password).not.toBeUndefined();

The screenshot proves that the correct information is being selected: screenshot from playwright

So I assume that my issue is that the assignment of the consts is messing up due to the await.

I do see a TS error ts(2345) if I try to modify the hardcoded value from the codegen with my const:

await page.getByPlaceholder('Brugernavn').fill(username);

But I am not sure how I should fix the issue. most of my searchning has indicated that I should change the return value of the call in the await - But I cannot, since it is a playwright function.


Solution

  • Reading along in the documentation locator.selectText returns Promise<void>

    So I tried locator.innerText instead, which returns Promise<string>

    and that solved the issue.