End-to-end tests with Playwright: stable locators, waiting and isolated test data
End-to-end tests are the most convincing evidence that an application actually works: a real browser opens, it is clicked like a real user would click it, and a real server answers. They are also the tests a team loses trust in fastest. A test that passed yesterday is red today, turns green when you rerun it, and after a while nobody takes a red result seriously.
That flakiness is mostly a consequence of how the test is written, not of the tool. In this post I walk through a few basic decisions that keep end-to-end tests stable, using Playwright: choosing what to test, how to find elements, what to wait for, how to isolate data and how to find out why a test failed.
What belongs in an end-to-end test?
An end-to-end test is slow and expensive; it brings up the browser, the frontend, the API and the database at the same time. Trying to verify every rule here is therefore the wrong goal. Ten different invalid values for a form field are checked much faster and more clearly in a component test, and the edge cases of a price calculation in a unit test.
Where an end-to-end test is strong is in the parts working together: routing, authentication, the real API contract, the real database schema. It is enough to put a small number of flows in this layer, the ones that make the product unusable when they break: signing up, signing in, placing an order, paying, creating a record and finding it again. Each test should describe an outcome a user wants to reach, not individual screens.
Keeping the number small is not a weakness. Ten reliable flow tests catch more bugs than a hundred tests of which half fail now and then, because a red result still means something.
Finding elements the way a user sees them
The first source of brittle tests is selectors. A CSS selector such as div.card > button.btn-primary:nth-child(2) depends on the internal structure the page happens to have that day. A layout change breaks the test even though the behaviour has not changed at all.
Playwright's locators let you find an element the way the user perceives it: by its role, its visible name, its label.
await page.getByLabel('Email').fill('[email protected]');
await page.getByRole('button', { name: 'Complete order' }).click();
await expect(
page.getByRole('heading', { name: 'Your order has been received' })
).toBeVisible();
This approach has two side benefits. First, reading the test tells you what the user does. Second, if a button cannot be found by its role and name, that often means someone using a screen reader cannot find it either; the test indirectly probes accessibility as well.
There are cases where role and text are not enough: several elements with the same name, icon buttons without text, text that changes often or gets translated. Narrowing the scope first helps: a chained locator such as page.getByRole('row', { name: 'Invoice 1042' }).getByRole('button', { name: 'Delete' }) targets the button in the right row. If that is not enough either, a data-testid attribute with getByTestId is an honest solution: it is obvious that it exists for testing, and it is unaffected by styling changes.
Waiting for a condition, not a fixed time
The second major source is timing. After a button is pressed, it takes a moment for the result to appear, and the solution that looks easiest is to put page.waitForTimeout(2000) in between. That line is wrong in two ways: on a fast machine it waits for nothing, and on a slow CI machine two seconds are not enough and the test fails.
In Playwright this is not needed. Actions wait on their own until the target element is visible and ready for interaction. Assertions written with expect(locator) also retry until the condition holds or the timeout expires. So waiting is not about stating a duration; it is about stating the next state the user will see.
The subtle trap here is assertions that do not retry:
// Does not retry: reads the value at that moment and compares
expect(await page.getByTestId('cart-count').textContent()).toBe('3');
// Retries until the condition holds
await expect(page.getByTestId('cart-count')).toHaveText('3');
The first line fails if it runs before the counter has been updated. The second verifies the same thing but lets the interface catch up. The same reasoning applies to page transitions: instead of indirect signals such as "wait until the network is quiet", asserting the heading or URL that should appear on the new page is more reliable.
If a test only passes once you add a wait, the application itself is usually telling you something: a signal that shows the user the operation is in progress or finished is missing. Adding that signal improves both the test and the product.
Every test creates its own data
Behind tests that pass when run alone and fail in a full run, there is almost always shared data. One test creates a record called "Sample Project", another deletes it, a third expects exactly five records in the list. Once tests start running in parallel, the order becomes undefined and the failures look random.
The rule is simple: a test creates the data it needs itself and makes no assumptions about the data of other tests. Because preparing data by clicking through the interface is slow, a good balance is to do the setup directly through the API and run only the flow under test in the browser. Playwright's fixture mechanism makes this reusable:
import { randomUUID } from 'node:crypto';
import { test as base, expect } from '@playwright/test';
type Project = { id: string; name: string };
export const test = base.extend<{ project: Project }>({
project: async ({ request }, use) => {
const name = `e2e-${randomUUID()}`;
const response = await request.post('/api/projects', { data: { name } });
expect(response.ok()).toBeTruthy();
const project: Project = await response.json();
await use(project);
await request.delete(`/api/projects/${project.id}`);
},
});
Every test that asks for the project parameter gets its own record with a unique name; when the test ends, the line after the use call runs and the record is deleted. The unique name also makes assertions more robust: saying "the list shows the name of my project" instead of "the list has five rows" stays true even when the environment contains other data.
Cleanup should not be relied on alone; a process that crashes in the middle of a test leaves data behind. Resetting the test environment at regular intervals, or marking the records tests produce with a recognisable prefix and deleting them in bulk, keeps the environment from getting polluted over time.
Signing in once and reusing the session
Filling in the login form at the start of every test both lengthens the run and turns a single problem on the login page into a failure of every test. The common solution in Playwright is to sign in once in a separate setup step and save the browser state to a file:
// auth.setup.ts
import { test as setup, expect } from '@playwright/test';
setup('sign in', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill(process.env.E2E_USER!);
await page.getByLabel('Password').fill(process.env.E2E_PASSWORD!);
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page.getByRole('link', { name: 'My account' })).toBeVisible();
await page.context().storageState({ path: 'playwright/.auth/user.json' });
});
In the configuration, this file is defined as a separate project and the actual tests are made dependent on it:
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
retries: process.env.CI ? 2 : 0,
use: {
baseURL: process.env.E2E_BASE_URL ?? 'http://localhost:3000',
trace: 'on-first-retry',
},
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup'],
},
],
});
The saved file contains cookies and local storage; in other words it is a real session credential and must not end up in version control. The sign-in flow itself gets its own test; the other tests assume the session exists. If tests modify server-side state that belongs to the user, using a separate test account for each parallel worker prevents one test from breaking another's settings.
Stopping external services at the network boundary
The value of an end-to-end test lies in talking to the real backend; if you mock your own API, what you are left with is an expensive component test. Third-party services outside your control are a different matter: the payment provider, maps, analytics. They can be slow, they can apply rate limits, and they do not produce the error case you want at the moment you want it.
Requests of this kind that leave the browser can be intercepted with page.route and answered with a fixed response:
await page.route('**/api/payments/authorize', route =>
route.fulfill({ status: 502, json: { error: 'gateway_unavailable' } })
);
await page.getByRole('button', { name: 'Complete payment' }).click();
await expect(page.getByRole('alert')).toContainText('Payment is currently unavailable');
This is the most practical way to test error paths that are hard to produce in a real environment. You need to know its limit: page.route only sees requests made by the browser. For calls your server makes in the background, the test environment has to use the provider's sandbox or a fake service. Whichever you choose, protecting the mocked response's agreement with the real contract through a separate test guards against mocks that drift away from reality over time.
Understanding a test that fails in CI
When a test that passes locally fails in CI and all you have is the line "element not found", what follows is usually guesswork. Playwright's tracing changes that. The trace: 'on-first-retry' setting in the configuration above records a DOM snapshot of every step, the network requests and the console output when a test fails for the first time and is retried. If you keep that file as a CI artifact and open it in the trace viewer, you can step through the page as it was at the moment of the failure.
Retries, on the other hand, are a tool to be used with care. One or two retries in CI keep transient infrastructure errors from stopping the whole pipeline. But a test that passes on retry should not count as a success; Playwright marks these tests separately as flaky in the report. That list needs to be watched, and every test in it treated like a bug report. Otherwise retries turn into a cover that hides real race conditions; a flaky test sometimes points to a defect in the application, not in the test.
Running in parallel shortens the run and is a good check at the same time: tests with incomplete data isolation give themselves away immediately in a parallel run. Aiming from the start for tests that can run in any order and at the same time is far cheaper than fixing it afterwards.
Closing
Stable end-to-end tests are the sum of a few decisions that each look small: choosing few but meaningful flows, finding elements the way the user sees them, waiting for conditions instead of durations, giving every test its own data, signing in once and stopping external services at a deliberate boundary. Once these are in place, a red test means something again: either the product is broken or the test has caught a real source of nondeterminism. Both are worth looking at, and thanks to the trace, looking takes minutes.