31 January 2023by Jack McGregor
This will be a short post because I'm tired:
At Antler we've recently implemented a new pattern for creating Playwright test ID selectors dynamically see here which I know is a bit of a Playwright anti-pattern but we only have the budget to use Playwright as smoke tests rather than fully-fledged E2E tests so time is money!
Furthermore, given that both the front-end and back-end teams have their own Playwright use-cases, we needed an easy way to get all the IDs on a page and ideally make them type-safe both for regressive tests and intellisense.
As a disclaimer, we use NextJS for our front-end so simply scraping the source files doesn't work:
Part 1: The scraper
The TLDR of this is function is that takes in the HTML as a string (eg "<body>/*...*/</body>"), uses a regex matcher to find all occurences of our selector (`data-playwright-id="<the_id_we_want>"`), and then parse them in 4 ways:
- Plain text
- JSON
- JS
- TS
You clearly don't need all of them but having the options is useful. In our case, since we want these typed for a better dev experience, we want to take the .ts files and create declaration files for them. We can do this by using the `typescript` package to emit only declaration files:
Part 2: The scraping
Ok we have the script, awesome, but right now it's a manual process. We're going to implement this into a separate Playwright script that will crawl, scrape, store and parse all of our selectors.
And there it is - when you run the script "yarn playwright:scrape" it will run playwright with a specific config which targets a specific directory which runs no tests, but instead runs our scraping script for each page that gets rendered. Pretty neat. After Playwright has run it will convert those files to declaration files so you can use intellisense in your tests like so:
Seed file for PayloadCMS23 January 2023Rendering languages in code blocks17 January 2023Creating dynamic test IDs for Jest and Playwright17 January 2023