← Back to Discord Forum

Coming from testing-library for experimental-ct tests

Hello all, I'm trying out @playwright/experimental-ct-react but I'm not sure I get how to use locators correctly.

Here is my test rewritten with playwright:

test("can interact", async ({ mount }) => {
  const screen = await mount(<App />);
  const button = screen.getByRole("button", { name: "count is 0" });
  await expect(button).toBeVisible();
  await button.click();
  await expect(button).toHaveText("count is 1");

The last assertion await expect(button).toHaveText("count is 1"); is failing (the locator cannot be found anymore). So I guess locators are static and are not refering to a DOM node?

What should I do to find the element again? Calling screen.getByRole again?


This thread is trying to answer question "What should I do to find the element again in `@playwright/experimental-ct-react` testing?"

6 replies

(with testing-library the above test was working)

it seems to answer my question

then what would be a good strategy here?

have a test-id on the button?

Hi, Locator objects are not element handles. They are lazy and re-evaluated every time you call a method on them.

Normally this provides more stability for the test automation because we are not holding on to a browser object, possibly leading to memory leaks, possibly getting detached, possibly getting re-used for something else during progressive re-rendering, etc.

But for it to be stable, you also need stable locator strategy, not referring to some properties that will change. There are several ways to go about that. Adding a test-id to the button will help.

Alternatively, you can use a regular expression in the getByRole name criterion. For example: const button = screen.getByRole("button", { name: /count is \d+/ });

Related Discord Threads

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.