Skip to main content

Codegen: record, then rewrite

Why This Matters

The recorder is the fastest way to find out how Playwright would locate an element, and a poor way to write a test you will maintain. A recording captures every click you made, including the ones that do not matter, and it never says what should be true afterwards. Use it to discover; then write the test yourself.

Start the recorder

npx playwright codegen --viewport-size=1280,720 https://practiceautomatedtesting.com/shopping

Two windows open: a browser, and the Playwright Inspector, which writes code while you click. --viewport-size makes the recording use the same window size as your tests; without it, the browser gets whatever size your screen gives it.

This is a real recording on the practice site: search for “lamp”, add the Desk Lamp to the cart, add an assertion, then pick a locator.

A real codegen session on the practice site: typing lamp in the search box, clicking Add to Cart on the Desk Lamp, adding a text assertion, and hovering with Pick locator

The toolbar

The browser gets a small floating toolbar at the top of the page. The Inspector has the same buttons:

ButtonWhat it does
⏺ RecordTurns recording on and off. While it is on, every click and every keystroke becomes a line of code.
↖ Pick locatorHover over any element to see the locator Playwright would use. Click to copy it to the Locator tab. Nothing is recorded.
👁 Assert visibilityClick an element to add toBeVisible() for it.
ab Assert textClick an element to add toContainText(). A small dialog shows the text, which you can edit first.
▭ Assert valueFor a field: adds toHaveValue() with what is in it now.
{} Assert snapshotAdds toMatchAriaSnapshot(): the structure of the element as the accessibility tree sees it.

On the right of the Inspector toolbar: Copy, Resume, Pause, Step over (for stepping through a test), and Clear, which empties the recorded test. Target selects the output language: Test Runner gives a Playwright Test file in TypeScript.

The Assert text dialog: after clicking the Add to Cart button, the recorder proposes to assert that it contains “Add to Cart”

What the recording produced

This is the Inspector right after the recording in the GIF:

The Playwright Inspector with the recorded test on the right, and the Locator tab showing getByRole(‘heading’, { name: ‘Desk Lamp’ })

The code, exactly as recorded:

test('test', async ({ page }) => {
  await page.goto('https://practiceautomatedtesting.com/shopping');
  await page.getByText('E-commerce Testing Practiceshopping_c…').click();   // cut off in the Inspector
  await page.getByTestId('search-input').click();
  await page.getByTestId('search-input').fill('lamp');
  await page.getByTestId('add-to-cart-9').click();
  await expect(page.getByTestId('add-to-cart-9')).toContainText('Add to Cart');
});

Every problem a recording can have is in these six lines:

  • Line 2 is an accident. A click on the page before the real work started was recorded too, with a text locator built from everything in that area, including the icon text shopping_cart (the locator lesson explains why that text is not part of the accessible name, but is part of the text). It does nothing useful and breaks as soon as the cart contents change.
  • The assertion checks nothing. Assert text was clicked on the Add to Cart button, because the cart button had scrolled out of view, so the test now checks that a button says “Add to Cart”. The recorder asserts whatever you click; choosing the element that proves the behaviour is your job.
  • Test ids everywhere. When an element has a data-testid, codegen prefers it over a role. That is why the clicks use getByTestId('add-to-cart-9'), while the picker, hovering over the heading (which has no test id), suggests getByRole('heading', { name: 'Desk Lamp' }).
  • The full URL, the extra click() before fill(), and the name 'test': the same as in any recording.

What to keep, what to change

RecordedProblemRewrite
A click you did not meanNoise, and often a fragile text locatorDelete it
The full URL in gotoIgnores baseURL; breaks on another environmentpage.goto("/shopping")
click() before fill()fill() focuses the field itselfDrop the click
getByTestId('add-to-cart-9')Correct, but who is product 9?Find the card by its heading, then the button
An assertion on the element you clickedChecks the UI’s labels, not the behaviourAssert the outcome: the cart button, the result count
test('test', …)Says nothing in a reportName the behaviour

The rewrite, the way the module 2 tests are written:

test("the Desk Lamp can be found and added to the cart", async ({ page }) => {
  await page.goto("/shopping");
  await page.getByRole("textbox", { name: "Search for items" }).fill("lamp");

  const lamp = page.getByTestId(/^product-\d+$/).filter({ hasText: "Desk Lamp" });
  await expect(lamp).toHaveCount(1);
  await lamp.getByRole("button", { name: "Add to Cart" }).click();

  await expect(page.getByTestId("cart-button")).toContainText("1 items");
});

Useful options

OptionUse it for
--viewport-size=1280,720The same window size as your tests
--device="iPhone 13"Recording a mobile layout
--save-storage=auth.json / --load-storage=auth.jsonLog in once, save the session, and start later recordings already logged in (module 4)
--test-id-attribute=data-testWhen your application uses another attribute than data-testid
-b webkitRecording in another browser
-o recorded.spec.tsWriting the recording to a file instead of only to the Inspector

In VS Code, the Playwright extension has Record new and Record at cursor, which record straight into an existing test file. The same rules apply: record to discover, then rewrite.

Pick a locator without recording

Pick locator is often all you need from the recorder: hover over an element, read the locator, copy it. The same picker is in UI mode (next lesson). As the recording shows, the suggestion is a good start, not a verdict: the picker does not know that two cards contain “wireless”, or that a test id hides which product you mean. Lesson 8 covers those decisions.

Exercise

Record the checkout flow: add the Bluetooth Headphones, open the cart, and increase the quantity to 2 with the + button. Then rewrite the recording into a test that asserts the line shows quantity 2 and the subtotal is $119.98.

Show suggested solution
test("increasing the quantity updates the subtotal", async ({ page }) => {
  await page.goto("/shopping");
  await page.getByTestId(/^product-\d+$/).filter({ hasText: "Bluetooth Headphones" })
    .getByRole("button", { name: "Add to Cart" }).click();
  await page.getByTestId("cart-button").click();

  const checkout = page.getByTestId("checkout-modal");
  await checkout.getByTestId("cart-increase-5").click();
  await expect(checkout.getByTestId("cart-qty-5")).toHaveText("2");
  await expect(checkout.getByTestId("cart-subtotal")).toHaveText("$119.98");
});

The quantity buttons have no accessible name beyond “+” and “−”, so the site’s test ids (cart-increase-5, cart-qty-5) are the clearer handle here. The recording had the clicks; the assertions are what you added.