Let's have a look at how to use Playwright's Codegen tool to generate automated browser tests.
If you would like to learn more about Playwright, checkout my previous blog on Getting started with Playwright. As per this last post, we can write our tests but we can also use their test generation tool Codegen.
We can get started by using command line: npx playwright codegen plus the domain we want to test. For example the below will generate tests for this website:
npx playwright codegen https://carole.dev
This will open 2 windows: the browser for this domain aswell as a Playwright window. As we interact with the website, it will generate our tests! In the browser window, click around some links. Now if we look in the playwright tool, we'll see it has generated some tests.
Now we can copy the code and put it in to a file like in our getting started tutorial. I have called mine carole-codegen.spec.Now, we can call:
npx playwright test
It will run our tests as usual, we can get a report as with any Playwright tests.
We can add parameters to the command line before launching Codegen. This will provide the context for scenarios we want to test. Here are some examples:
npx playwright codegen -b firefox https://carole.dev
This tests specifically in Firefox browser.
npx playwright codegen --device "Pixel 5" https://carole.dev
This tests emulating Pixel 5 android device.
npx playwright codegen --viewport-size "900, 400" https://carole.dev
This tests in a specific browser viewport size.
npx playwright codegen --lang "en-GB" https://carole.dev
This test will open in a local based on the language provided.
To see all cmd parameters available, we can call:
npx playwright codegen -h
Have a look at the script generated for each of the scenarios available. It is a great way to learn how to write Playwright tests for many different test scenarios. This will help with your understanding of the framework and be really useful as you want to create more complex automated tests.