Skip to main content

Test generator

Introduction

Playwright comes with the ability to generate tests for you as you perform actions in the browser and is a great way to quickly get started with testing. Playwright will look at your page and figure out the best locator, prioritizing role, text and test id locators. If the generator finds multiple elements matching the locator, it will improve the locator to make it resilient that uniquely identify the target element.

Generate tests with the Playwright Inspector

When running the codegen command two windows will be opened, a browser window where you interact with the website you wish to test and the Playwright Inspector window where you can record your tests and then copy them into your editor.

Running Codegen

Use the codegen command to run the test generator followed by the URL of the website you want to generate tests for. The URL is optional and you can always run the command without it and then add the URL directly into the browser window instead.

mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="codegen demo.playwright.dev/todomvc"

Recording a test

Run the codegen command and perform actions in the browser window. Playwright will generate the code for the user interactions which you can see in the Playwright Inspector window. Once you have finished recording your test stop the recording and press the copy button to copy your generated test into your editor.

With the test generator you can record:

  • Actions like click or fill by simply interacting with the page
  • Assertions by clicking on one of the icons in the toolbar and then clicking on an element on the page to assert against. You can choose:
    • 'assert visibility' to assert that an element is visible
    • 'assert text' to assert that an element contains specific text
    • 'assert value' to assert that an element has a specific value

recording a test

When you have finished interacting with the page, press the record button to stop the recording and use the copy button to copy the generated code to your editor.

Use the clear button to clear the code to start recording again. Once finished, close the Playwright inspector window or stop the terminal command.

Generating locators

You can generate locators with the test generator.

  • Press the 'Record' button to stop the recording and the 'Pick Locator' button will appear.
  • Click on the 'Pick Locator' button and then hover over elements in the browser window to see the locator highlighted underneath each element.
  • To choose a locator, click on the element you would like to locate and the code for that locator will appear in the field next to the Pick Locator button.
  • You can then edit the locator in this field to fine tune it or use the copy button to copy it and paste it into your code.