How to click a "type=submit" button in Playright

7.3k Views Asked by At

I tried any possible way to click a "type=submit" button in a form, but it doesn't click the button, the only way is by using "text = ' Register '" but I can't use the text because the form language may change based on the UI language selected by the user.

public Task ClickRegister() => Page.Locator("type=submit").ClickAsync();

Here is the FE code:

<button _ngcontent-yyv-c173="" type="submit" class="btn btn-primary"> Register </button>

I'm using Visual Studio

4

There are 4 best solutions below

0
On BEST ANSWER

That's not a valid selector. Can you try something like BUTTON[type="submit"]?

0
On

To complete @evanion answer, you can use either of these 2 options:

  • await page.getByRole('button', { name: 'Register' }).click();
  • await page.locator("[type=submit]").click();
3
On

There's a few ways to tackle this, any of the following will work:

  • button.btn (combination of element button and partial class btn)
  • button.btn.btn-primary (combo of element and full class btn btn-primary)
  • button.btn-primary (combo of element and unique part of class btn-primary)
  • button.btn.btn-primary[type="submit"] (combo of element, full class and attribute type)
  • .btn.btn-primary (just the full class)

If you have pages that have a "Register" like button on the right, "Cancel" like button on left, "Accept" cookies button on a banner, your CSS selector button[type=submit] may be brittle, hence i would recommend to use the full class as the unique identifier, e.g. button.btn-primary for Register, or button.btn-primary.pull-left for Cancel. Also you may find the developer has put the button in a row class layered in the DOM which you can utilise to make it less brittle, e.g. .btn-row button.btn-primary.

You can get more info on CSS selector combinations from W3Schools - CSS Selector Reference

0
On

While it's possible to select an element using class selectors, it's not a good pattern. In e2e tests you should only use ways that the user can use when targeting an interactive element.

And only use testid or other forms of selectors (like class selectors) when targeting none interactive elements.

await page.getByRole('button', {name: 'Sign In'})

This would target a button with the text Sign In.

  • Your e2e test should be stable in it's "alignment" (url, locale, etc).
  • Then you can move on to the "act" phase, this is were you preform all the actions.
  • Before finally coming to the "analyse" phase (where you "expect" stuff).

Your e2e tests should mock the API calls so that it can be run with out going against an actual backend.