Tests that depend on each other can't run in parallel, hardcoded waits make a suite slow and still flaky, and repeated locator chains scattered across files mean one UI change breaks dozens of tests. The fixes are descriptive test names, isolated state, element-based waiting instead of waitForTimeout, and Page Object Model once files get long.
Key takeaways
- Each test sets up its own state, either by logging in itself or by starting from a saved
storageState(cookies and local storage), so it can run alone and in parallel and one failure does not cascade into the others. - A fixed wait such as
waitForTimeout(3000)is slow on fast machines and still flaky on slow CI runners. Wait for the element or the response the test needs. - A
test.onlythat reaches main makes CI run one test and pass.forbidOnly: !!process.env.CIinplaywright.config.tsturns that into a failure. - Name a test as a sentence ("login fails with incorrect password") and give it one logical concept, so a CI failure tells you what broke without opening the code.
- Group test folders by feature (
tests/auth/), not by type, and set the structure up early while moving files is cheap.
Name tests like sentences, not like code
The test name is the first thing you read when a test fails in CI, and it should tell you what broke without opening the file.
Bad:
test('login test', async ({ page }) => { ... });
test('test1', async ({ page }) => { ... });
test('checkTable', async ({ page }) => { ... });Good:
test('user can log in with valid credentials', async ({ page }) => { ... });
test('login fails with incorrect password', async ({ page }) => { ... });
test('travel items table shows 5 rows after login', async ({ page }) => { ... });Follow the pattern [who] can/cannot [do what] [under what condition]. Write it so a non-technical person reading the CI output understands what failed.
describe blocks work the same way:
test.describe('Login', () => {
test('succeeds with valid credentials', async ({ page }) => { ... });
test('fails with wrong password', async ({ page }) => { ... });
test('fails with empty email', async ({ page }) => { ... });
});One concept per test
You'll see the advice "one assertion per test." A workable rule is one logical concept per test.
A test that logs in and checks the page title is fine, because both belong to one flow. A test that logs in, checks the title, edits a record, checks the record updated, then logs out is doing too much. When it fails you won't know which part broke.
Good. One concept, several related assertions:
test('login redirects to dashboard with correct header', async ({ page }) => {
await page.goto('https://lab.becomeqa.com');
await page.getByRole('button', { name: 'Login' }).click();
await page.getByLabel('Username').fill('admin@becomeqa.com');
await page.getByLabel('Password').fill('testpass123');
await page.getByRole('button', { name: 'Submit' }).click();
await expect(page).toHaveURL(/dashboard/);
await expect(page.getByRole('heading', { level: 1 })).toBeVisible();
await expect(page.getByText('My Travel Items')).toBeVisible();
});Keep tests independent from each other
If test 3 only works when test 2 has run first, you can't run it alone or in parallel, and when test 2 breaks the failures cascade and are hard to diagnose.
Every test must set up its own state and clean up after itself.
Each test that needs a logged-in user should do the login itself, or use storageState to save the signed-in state (cookies and local storage) once and reuse it without repeating the UI flow.
// Bad: depends on previous test having logged in
test('can see travel items', async ({ page }) => {
// assumes we're already logged in — breaks if run alone
await expect(page.getByText('My Travel Items')).toBeVisible();
});
// Good: sets up its own state
test('can see travel items', async ({ page }) => {
await page.goto('https://lab.becomeqa.com');
await page.getByRole('button', { name: 'Login' }).click();
await page.getByLabel('Username').fill('admin@becomeqa.com');
await page.getByLabel('Password').fill('testpass123');
await page.getByRole('button', { name: 'Submit' }).click();
await expect(page.getByText('My Travel Items')).toBeVisible();
});test.only. It skips every other test in the run, so a merged test.only makes CI pass with one test instead of 50 until something breaks in production. Set forbidOnly: !!process.env.CI in playwright.config.ts and CI fails when one is left in.Use Page Object Model once files get large
When your test file gets long and every test repeats the same getByLabel('Username').fill(...) calls, it's Page Object Model in Playwright: From Messy to Maintainable (POM).
POM moves page interactions into a separate class. Tests call methods on that class instead of raw Playwright commands. When the login form changes, you update one class instead of every test that touches login.
// pages/LoginPage.ts
import { Page } from '@playwright/test';
export class LoginPage {
constructor(private page: Page) {}
async goto() {
await this.page.goto('https://lab.becomeqa.com');
await this.page.getByRole('button', { name: 'Login' }).click();
}
async login(username: string, password: string) {
await this.page.getByLabel('Username').fill(username);
await this.page.getByLabel('Password').fill(password);
await this.page.getByRole('button', { name: 'Submit' }).click();
}
}// tests/login.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
test('user can log in', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login('admin@becomeqa.com', 'testpass123');
await expect(page.getByText('My Travel Items')).toBeVisible();
});Don't rush to POM. Write tests without it first, and extract a page object when you catch yourself copy-pasting the same block for the third time.
Avoid hardcoded waits
page.waitForTimeout(3000) is a code smell. You're telling Playwright to wait 3 seconds regardless of what's on the screen. The test becomes slow on fast machines and still flaky on slow CI runners.
Playwright auto-waits for elements before interacting with them. To wait for something else, wait for that exact thing:
// Bad
await page.waitForTimeout(3000);
await page.getByRole('button', { name: 'Save' }).click();
// Good — Playwright waits automatically before clicking
await page.getByRole('button', { name: 'Save' }).click();
// Good — wait for a specific element to appear
await expect(page.getByTestId('success-toast')).toBeVisible();
// Good — wait for a network response (start waiting before the action that triggers it)
const responsePromise = page.waitForResponse(resp => resp.url().includes('/api/items'));
await page.getByRole('button', { name: 'Save' }).click();
await responsePromise;waitForTimeout is acceptable only in local debugging, to slow a run down and watch it. Keep it out of committed test code.
Use environment variables for credentials and URLs
Hardcoded credentials and base URLs leak into git history, and changing them means searching every test file.
Store them in a .env file and load it in playwright.config.ts with the dotenv package (npm i -D dotenv). Playwright does not read .env files on its own.
# .env (never commit this file)
BASE_URL=https://lab.becomeqa.com
TEST_USER=admin@becomeqa.com
TEST_PASS=testpass123// playwright.config.ts
import { defineConfig } from '@playwright/test';
import dotenv from 'dotenv';
dotenv.config();
export default defineConfig({
use: {
baseURL: process.env.BASE_URL || 'https://lab.becomeqa.com',
},
});// tests/login.spec.ts
test('user can log in', async ({ page }) => {
await page.goto('/');
await page.getByRole('button', { name: 'Login' }).click();
await page.getByLabel('Username').fill(process.env.TEST_USER!);
await page.getByLabel('Password').fill(process.env.TEST_PASS!);
await page.getByRole('button', { name: 'Submit' }).click();
await expect(page.getByText('My Travel Items')).toBeVisible();
});Add .env to .gitignore. In CI, set the environment variables in the pipeline config instead.
Structure your test folder before it grows
Set up the folder structure early, while moving files is still cheap:
tests/
auth/
login.spec.ts
logout.spec.ts
items/
items-list.spec.ts
items-crud.spec.ts
api/
items-api.spec.ts
pages/
LoginPage.ts
ItemsPage.ts
fixtures/
auth.fixture.tsGroup by feature, not by type. tests/auth/ is better than tests/ui/ because when something in auth breaks, you know exactly where to look.
npx playwright test tests/auth/ to run only the tests in a folder. Useful when you're working on a specific feature and don't want to wait for the full suite.Write tests that document intent
Variable names should describe what they hold, test data should look realistic, and comments should only appear for non-obvious setup.
// Hard to understand
const u = 'admin@becomeqa.com';
const p = 'testpass123';
await page.getByLabel('Username').fill(u);
// Clear
const adminEmail = 'admin@becomeqa.com';
const adminPassword = 'testpass123';
await page.getByLabel('Username').fill(adminEmail);Run the full suite before merging
Connect your Playwright tests to CI so they run on every pull request.
At minimum, CI should install dependencies, install browsers, and run the suite:
# .github/workflows/tests.yml (simplified)
- run: npm ci
- run: npx playwright install --with-deps
- run: npx playwright testA failing run blocks the merge until you fix the test or the bug.
FAQ
How do I replace waitForSelector and waitForTimeout in an old suite?
Replace waitForSelector with a web assertion such as expect(locator).toBeVisible() or with locator.waitFor(), since the Playwright docs list page.waitForSelector as discouraged. Remove waitForTimeout from committed tests, because Playwright already auto-waits before each action.
When do I introduce Page Object Model, and when is it too early?
Write the tests without it first. Introduce it when you copy the same locator block for the third time or the file gets long, and not before.
Why does my .env file have no effect?
Playwright does not load .env on its own. Install dotenv, call dotenv.config() in playwright.config.ts, and keep .env in .gitignore.
→ See also: Page Object Model in Playwright: From Messy to Maintainable | Custom Fixtures in Playwright: The Pattern That Makes Tests Read Like Prose | Flaky Tests: Why They Happen and How to Eliminate Them | Test Isolation: Why Each Playwright Test Should Be Stateless