Skip to content

Codegen

Codegen opens a browser and Inspector side-by-side — your interactions become Playwright code with recommended locators in real time.

Recording Tests

Run npx playwright codegen localhost:3000 — click through flows, copy generated code into spec files, then refactor duplicates into page objects.

Codegen highlights locators on hover and prefers getByRole and getByText over CSS.

npx playwright codegen http://localhost:3000/login
npx playwright codegen --target=javascript
npx playwright codegen --save-storage=auth.json  # save login state

--save-storage helps record flows that require authentication.

Codegen Options

--target=playwright-test   TypeScript test format
--load-storage=auth.json   Start authenticated
-o tests/recorded.spec.ts   Save output to file
--device="iPhone 14"       Record mobile
  • Always review and trim recorded code before committing.
  • Replace fragile sequences with page object methods.
  • Record on same baseURL environment tests use.
  • Use load-storage for post-login flows.

Codegen Reference

Common codegen commands.

Command Purpose
codegen <url> Record from URL
--save-storage Save auth after recording
--load-storage Start with auth
--device Mobile recording
-o file.spec.ts Write directly to file
Copy from Inspector Manual copy per action

Refining Recorded Tests

  • Remove redundant waits codegen may add.
  • Extract repeated flows to fixtures.
  • Add assertions codegen omitted.
  • Replace duplicate locators with variables.

Adding Assertions After Codegen

Codegen records actions, not expectations. Always add await expect(...) after recording to define test success criteria.

Common Mistakes

  • Committing raw codegen output without assertions.
  • Recording against production with real data.
  • Not adding test.describe or meaningful test title.
  • Trusting nth() locators codegen uses on ambiguous elements.

Key Takeaways

  • Codegen accelerates initial test creation.
  • Output prefers user-facing locators.
  • Refactor recordings into maintainable specs.
  • save/load-storage handles auth during record.

Pro Tip

Record once, then delete redundant clicks (double navigations) — codegen is verbose by design.