Your Playwright Codegen Test Failed in CI. Here’s Why (and the 3 Fixes)

Playwright Codegen TestPlaywright Codegen Test

What Will You Read in This Blog?

  • Why your Codegen test passed locally and failed in CI within 48 hours the exact mechanism, not a vague “flakiness” answer.
  • The three Codegen pitfalls, stated upfront so you can fix your test while skimming.
  • The one-line edit for each pitfall, with before/after code you can paste.
  • What to do when Codegen generates 40 lines when you meant 6 the recording mode almost nobody uses.
  • The two decisions Codegen must never make for you.
  • A full before/after refactor of a real recorded test.

Playwright Codegen Test – The Failure, First

You ran npx playwright codegen, clicked through your login flow, got a clean-looking test, committed it. It passed locally. CI went red 48 hours later.

That’s not bad luck, and it isn’t Playwright being unreliable. Codegen recorded what you did, not what you meant. Three specific things in its output cause almost every post-commit failure, and all three are visible in your file right now:

// Your Codegen output; all three problems in five lines
await page.locator('#root > div > div:nth-child(2) > button').click();  // 1
await page.waitForTimeout(800);                                         // 2
// (no assertion anywhere in the test)                                  // 3
Playwright Codegen Test

1. A structural CSS selector that breaks the moment a <div> is added for layout.
2. A waitForTimeout that is your reaction time, not your app’s latency so CI, which is slower than your laptop, outruns it.
3. Zero assertions, meaning the test cannot fail unless the page crashes. It clicks four things, passes regardless of outcome, and tells you nothing.

Each has a one-line fix. Here they are, in the order that matters.


Fix 1: Replace Structural Selectors with Role Locators

// Codegen gave you:
await page.locator('#root > div > div:nth-child(2) > button').click();

// Merge this:
await page.getByRole('button', { name: 'Submit order' }).click();

The CSS path is unique today. The moment anyone wraps that button for layout, it points at nothing and the failure surfaces as a confusing timeout, not an obvious selector error. Role locators are tied to what the user sees, so they survive redesigns, CSS-in-JS migrations, and class renames.

If getByRole throws a strict-mode violation, that’s the feature working: it matched two elements, meaning your test was about to click the wrong one. Narrow it with { exact: true } or scope it: page.getByRole('dialog').getByRole('button', ...).

Full locator strategy: if you want the complete priority ladder why role beats label beats test-id beats CSS, and when data-testid is still the right call that’s covered in Your Tests Aren’t Flaky. Your Locators Are.. Read it before you rewrite your second recorded test; rewriting the first one by hand teaches you the pattern, but the ladder saves you from guessing on the rest.


Fix 2: Delete Every waitForTimeout and Assert Instead

Codegen inserts waits where it “detected” a delay. Those numbers are your pause, not your application’s. Delete all of them and assert on the state you were actually waiting for:

// Codegen gave you:
await page.locator('.modal .btn').click();
await page.waitForTimeout(800);

// Merge this:
await page.getByRole('button', { name: 'Save changes' }).click();
await expect(page.getByRole('dialog')).toBeHidden();

toBeHidden(), toBeVisible(), toHaveURL(), toHaveText() auto-retry until they pass or time out. waitForTimeout does not retry anything it just burns a fixed number of milliseconds and hopes. On a fast laptop that hope holds. On a loaded CI runner it doesn’t.

If you don’t know what state you were waiting for, that’s worth discovering before you commit the test. It usually means the flow isn’t fully understood yet.


Fix 3: Add at Least One Assertion Before Merging

A Codegen login test typically looks like this:

await page.goto('https://app.example.com/login');
await page.getByLabel('Email').fill('[email protected]');
await page.getByLabel('Password').fill('password123');
await page.getByRole('button', { name: 'Sign in' }).click();

Nothing is asserted. This test cannot fail. It clicks and passes whether login worked, whether you were redirected to an error page, or whether the button did nothing at all.

await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL('/dashboard');
await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();

Rule: no recorded test merges without at least one web-first assertion. An assertion-free test verifies the page didn’t throw which is a smoke test’s job, not a regression suite’s.

One config detail matters here: a test that now asserts on URL changes will fail differently depending on your expect timeout. If you’re seeing assertions time out at 5 seconds when the app takes 8, that’s a config decision, not a test bug covered in Playwright Setup 2027, under the expect: { timeout } setting.


When Codegen Gives You 40 Lines Instead of 6

Codegen has two recording modes, and most people only use the default:

  • Full-page recording captures every interaction on the page including accidental clicks on containers you hovered over.
  • Record at cursor only records interactions with the element your cursor is on.

If you’ve ever recorded a simple form and gotten a wall of incidental clicks, you were in full-page mode on a UI with nested click handlers. Toggle to record-at-cursor and the output drops to roughly what you intended.


The Two Things Codegen Must Never Decide

  1. Assertions. If Codegen could infer success criteria, it would be a test framework, not a recorder. You define what “worked” means.
  2. Test structure. Codegen dumps everything into one flat test('test', ...). Real tests are named for one behavior and stay focused. Merge Codegen’s output into a structured test—don’t ship its raw output as one.

Before and After

Codegen output (do not merge):

test('test', async ({ page }) => {
  await page.goto('https://app.example.com/');
  await page.locator('#root > div > div > button').click();
  await page.waitForTimeout(800);
  await page.locator('.modal .btn').click();
});

Merge-ready:

test('opens settings modal and saves changes', async ({ page }) => {
  await page.goto('/');
  await page.getByRole('button', { name: 'Settings' }).click();
  await expect(page.getByRole('dialog')).toBeVisible();
  await page.getByRole('button', { name: 'Save changes' }).click();
  await expect(page.getByRole('dialog')).toBeHidden();
});

Six lines instead of five. One of these is still passing in 2028.


Do This Now

Pick one recorded test in your suite. Rewrite three locators to role-based. Delete one waitForTimeout and replace it with an assertion on the resulting state. Add one toHaveURL. That’s ten minutes of work. Run it twice in CI and compare it to an unreworked test.


FAQ

Can I merge Codegen output directly?
No. Use it as a starting point, then apply all three fixes before committing.

Why does Codegen prefer CSS selectors?
It optimizes for the shortest unique path, which is a machine criterion. Role locators require human judgment about what the element is.

Does record-at-cursor fix the selector problem?
No—it fixes volume, not quality. You still get CSS paths, just fewer of them.

Is Codegen worth using at all?
Yes. For fast discovery of the DOM structure and for scaffolding a flow, it’s genuinely faster than writing from scratch. It just isn’t a finished product.


Companion Video

Embed placement: directly after the “The Failure, First” section the video should sit where the reader has just seen the three problems and wants to see them happen.

Video title: Playwright Codegen: Auto-Generate Test Scripts Like Magic!

YouTube description (optimized for search + blog traffic):

Playwright Codegen generates a working test in seconds—then that test fails in CI two days later. This video shows the recording flow live and the three pitfalls in the generated output: structural CSS selectors, hard-coded waitForTimeout, and missing assertions.


Playwright Codegen: Auto-Generate Test Scripts Like Magic! 🚀 | Video Geeks

Continue the Series

This post is Part 3 of the Playwright 2027 series on videogeeks.in. If you landed here from search, the earlier parts cover the foundation this article assumes:

  • Part 1 – Playwright Setup 2027: Config, Projects & Test Isolation
    The config file, expect and action timeouts, parallel execution, and the browser-context model that makes every test in Part 3 run in isolation. Start here if your playwright.config.ts is still the one npm init playwright generated.
  • Part 2 – Your Tests Aren’t Flaky. Your Locators Are.
    The locator priority ladder (getByRole → getByLabel → getByTestId → CSS), web-first assertions, and the auto-waiting boundary. Start here if you’re rewriting the CSS selectors Codegen gave you and want to do it once, correctly.
  • Part 3 – this post. Why recorded Codegen tests fail in CI, and the three fixes that make them survive.

Coming next: Part 4 – Trace Viewer, where we diagnose the failures that CI logs can’t show you.

Leave a Reply

Your email address will not be published. Required fields are marked *