Search code examples
javascriptplaywright

In Playwright testing, how to click on Material UI datepicker button?


I am having trouble selecting the datepicker button to open the calendar, so I can select a date. The codegen runner suggests using the following code:
await page.getByRole('button', { name: 'Choose date, selected date is Feb 14, 2023' }).click();
That will only work if I know the previously selected date. I can use regex like
await page.getByRole("button", { name: /Choose date, selected date is/ }).click();
but that will break if there is more than one datepicker on the page.
I would like to either tab onto the button, and press enter, like
await page.getByLabel("Start date").press("Tab").press("Enter"); , Or if I could get the button inside that datepicker, maybe like
await page.getByLabel("Start date").getByRole("button").click();
but neither of those work, is there a way to do that?
Any other ideas?

Here is a sample test that will work when no date was previously selected (note I used first() because there are other datepickers on the page. This is what I need to avoid).

test("select from a date picker", async ({ page }) => {
  await page.goto("https://mui.com/x/react-date-pickers/date-picker/");
  await page.getByLabel("Basic Date Picker").click();
  const datepicker = await page
    .locator("div")
    .filter({ hasText: "Basic date picker" })
    .getByRole("button", { name: "Choose date" })
    .first();
  await datepicker.click();
  await page
    .getByRole("dialog", { name: "Basic date picker" })
    .getByRole("gridcell", { name: "14" })
    .click();
});

Solution

  • The reason why await page.getByLabel("Start date").getByRole("button").click(); does not work, is because the button is not nested under the date field, it is a sibling element.
    First you would need to get the parent, and then you can get the button inside it. .locator("..") will get the parent, as documented HERE

    await page.getByLabel("Start date").locator("..").getByRole("button").click();
    

    This will work, as long as there is only one start date on the page.