I’m using Playwright JavaScript to automate tests. This is the first time I’m going to try calling an element by data-testid
instead of id
or XPath. If I call an element by XPath like this, for example:
this.txtSearch = page.locator('xpath=//*[@id="root"]/div/main/section/div[1]/div[1]/div/div/input');
then it calls it correctly. However if I call it by data-testid
like this:
this.txtSearch = page.locator('[data-testid="SearchBar-InputText"]');
I get error:
Error: Timed out 5000ms waiting for expect(locator).toBeVisible()
Locator: locator('[data-test-id="SearchBar-InputText"]')
Expected: visible
Received: <element(s) not found>
Call log:
- expect.toBeVisible with timeout 5000ms
- waiting for locator('[data-testid="SearchBar-InputText"]')
Why could it be? Am I calling the wrong way for data-testid
?
5
PlayWright offers you a method getByTestId()
. You can read more at locate by test id.
So your locator has to be
this.txtSearch = page.getByTestId("SearchBar-InputText");
You can use either string or regex
getByTestId("SearchBar-InputText")
<- as stringgetByTestId(/SearchBar-InputText/)
<- as regex
If you need to change name of the attribute from e.g. data-testid
to testid
you have to do it in playwright.conf.ts
playwright.conf.ts
defineConfig({
...
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: process.env.BASE_URL,
.....
/* https://playwright.dev/docs/locators#locate-by-test-id */
testIdAttribute: '<your_custom_id>',
.....
}
})
4