grafana / xk6-browser

The browser module adds support for browser automation and end-to-end web testing via the Chrome Devtools Protocol to k6.
https://grafana.com/docs/k6/latest/javascript-api/k6-browser/
GNU Affero General Public License v3.0
342 stars 42 forks source link

Implement page.getBy* APIs #1226

Open ankur22 opened 8 months ago

ankur22 commented 8 months ago

Feature Description

Working with page.locator is better than working with page.$ since it allows us to work with elements on the page at any moment. These APIs both face the same issue which is that they work with XPath or CSS selectors which are cumbersome to use, hard to work with if you're not a frontend engineer, and depend on the DOM structure which can easily change. Having your tests depend on your DOM structure can lead to flakey/difficult to maintain failing tests (PW link to best practices)

Suggested Solution (optional)

Playwright has the following APIs on page:

getByAltText, getByLabel, getByPlaceholder, getByRole, getByTestId, getByText, and getByTitle.

They are less prone to DOM structure changes, instead working with use facing attributes. Take a look at these two and you will see that one is easier to understand than the other as well as less prone to DOM structures (which can be very flakey when id and class names are auto generated by the underlying frontend framework):

page.locator('button.buttonIcon.episode-actions-later');

vs

page.getByRole('button', { name: 'submit' });

Already existing or connected issues / PRs (optional)

https://github.com/grafana/xk6-browser/issues/784

2Steaks commented 5 days ago

This way of testing is all based on the principles designed by https://testing-library.com. It is the go-to testing library used by pretty much all frontend projects.

We have produced a version that integrates with k6 browser @grafana/testing-library-k6-browser which is currently private, but we would like to release it to the public. It actually injects @testing-library/dom into the browser context, executes the selector, and returns the result.

It is now in active use by the frontend team on the Grafana k6 plugin, examples of tests can be seen here