How do I record a test with Playwright codegen?
Written by Jatin Thacker, Automation Architect · Updated
npx playwright codegen followed by the page address, then click and type in the browser that opens while the Playwright Inspector writes the test code for each action. Copy the code, or save it with --output, and then read it critically before you keep it.This answer is one piece of Chapter 5: Your First Playwright Test.
Codegen is a recorder. According to the docs, it opens two windows: a browser where you use the site, and the Playwright Inspector, where the code appears as you go. It prefers role, text and test id locators, and makes a locator more specific when several elements match. Toolbar buttons add assertions for visibility, text and value.
It is a fast way to get the shape of a test and to find a locator for an awkward element. It is not a finished test. A recording repeats exactly what you did, including clicks you did not need, and only asserts what you asked it to. Review it the way you would review any test someone else wrote: are the checks meaningful, and would it fail if the feature broke?
Useful options: -o saves the script to a file, --device emulates a phone, --save-storage and --load-storage keep you signed in between recordings, and --block-service-workers matters on sites, like the practice app, that answer API calls from a service worker.
The recorder windows were not opened for this page. The output is three lines of the real --help text from this project's install.
$ npx playwright codegen https://practice.learnplayforge.com/login.html?seed=42
# Three of its options:
$ npx playwright codegen --help | grep -E -- "^ (-o, --output|--block-service-workers|--device)"-o, --output <file name> saves the generated script to a file --block-service-workers block service workers --device <deviceName> emulate device, for example "iPhone 11"
Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free