Testing keyboard accessibility: how to check what is selected with Playwright?

I have a React PWA that I am testing with Playwright.

I want to ensure everything in my PWA can be done using only the keyboard, so I want to write some tests in Playwright to verify this.

I use keyboard.press to input keys:

await this.page.keyboard.press('Tab');

Now, I want to verify which element is selected when I press the tab key.

So, for example, say I select an email field by pressing the Tab key three times like this:

await this.page.keyboard.press('Tab');
await this.page.keyboard.press('Tab');
await this.page.keyboard.press('Tab');

Now, I expect the result to be that I am now ready to type something into the email field. How can I verify that I have selected a given element? In other words, what can I use in Playwright to say "tell me the id of the element on the page that has been selected via the keyboard?"

I've been trying to Google this but I don't know the right term.

1 answer

  • answered 2022-05-06 05:42 Yevhen Laichenkov

    If you want to verify that the element is focused you can use toBeFocused matcher:

    await page.keyboard.press('Tab');
    await page.keyboard.press('Tab');
    await page.keyboard.press('Tab');
    await expect(page.locator('#email')).toBeFocused();

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum