End-to-end testing: when the cost is worth it
E2E tests cover what other layers can't — but they're expensive, slow, and prone to flakiness. When to use them, how many to write, and why retry isn't the fix.
An E2E (end-to-end) test is an automated test that walks through a flow of the system the way a user does: it opens the browser, clicks, types, and actually goes through the frontend, the API and the database. In a store's checkout, the E2E test logs in, adds a product, confirms the order and checks that the confirmation screen appeared. It's the test closest to production that exists, and also the most expensive.
The pipeline broke at 2 p.m. on a Friday. The culprit: an E2E test that had been flaky for three weeks, had never failed in development, and picked that exact Friday to decide the confirmation toast took longer than the test's fixed waitForTimeout. The deploy was blocked for forty minutes while someone ran it locally, confirmed everything was fine and re-ran CI. That's the real cost of a poorly calibrated E2E suite: not just execution time, but the cognitive cost of distrusting your own tests.
This post covers what E2E tests catch that no other layer does, when to use them, how many to have, and how to write tests that don't turn flaky, with Playwright examples I actually ran.
Where E2E sits relative to other tests
The testing pyramid sums up the economics: many cheap tests at the bottom, few expensive ones at the top. Unit tests run in milliseconds and point at the broken function; integration tests exercise a real database, cache and HTTP, but without a UI; E2E tests bring up everything, with a browser, server, database and sometimes email and webhooks. The difference between the two lower layers is detailed in unit test vs integration test.
The problem isn't writing E2E tests. It's writing them as if they were integration tests: lots of them, covering cases cheaper layers cover better.
What E2E covers that other layers don't
Before discussing quantity, it's worth understanding what justifies the cost.
Flows that cross several stateful systems. An integration test validates that the checkout API returns 200. An E2E test validates that the user clicked "Buy," filled in the card, saw the confirmation on screen and the order got saved. That includes session, cookies, redirects and DOM state, things integration tests don't exercise.
UI regressions with no backend representation. A form component that starts sending null instead of an empty string after a library upgrade won't show up in service tests. It shows up in E2E.
Frontend-backend contracts nobody noticed changed. The field became user_id instead of userId, and both sides have passing tests. The E2E test catches it because it exercises both together. A caveat, though: if this is your recurring problem, a contract test catches the same break much earlier and cheaper, with no browser.
All three cases have one thing in common: the bug only exists in the interaction between the parts.
When to use E2E tests
They pay off when regression risk is high and testing any other way is hard:
- Payment and checkout flows.
- Authentication, especially with OAuth and redirects.
- Multi-step onboarding with state persisted across screens.
- Features that already broke in production and that you want to keep from regressing.
They don't pay off for simple CRUD with validations already covered by unit tests, paginated listings with no logic, static pages, or field validation. "Invalid email shows an error message" is a unit test of the validation function, not a multi-second browser session. An isolated endpoint contract doesn't qualify either: that's the territory of automated API testing.
The question I ask before writing an E2E test: "if this test didn't exist, how would I know this broke?" If the answer is "through another faster, cheaper test," the E2E test doesn't need to exist.
How many E2E tests to have
Fewer than you're inclined to write. There's no universal ratio between unit, integration and E2E tests; fixed percentages like 70/20/10 are a convention, not a rule. What holds for any suite shape is that E2E tests stay few and reserved for critical flows.
The most common mistake is using E2E tests to cover variants. The sign-up flow has validations: invalid email, weak password, existing user, malformed tax ID. Someone writes an E2E test for each. Now there are eight tests taking tens of seconds each, depending on database state, sometimes failing on form timing, and covering cases a unit test covers in milliseconds.
The heuristic that works for me:
- One E2E test per critical business flow. Not per variant, not per edge case: per flow. Login, checkout, onboarding, subscription cancellation. Whatever stops the product if it breaks.
- The happy path of each critical flow, plus the error scenarios with a regression history.
- Zero E2E tests for validation logic and for isolated API contracts.
In my experience, that adds up to a few dozen tests for a mid-sized product. If the E2E count keeps growing, or the suite runs past twenty minutes or so, there's probably logic that should be covered further down.
Flaky tests: why retry isn't the fix
A flaky test sometimes passes and sometimes fails with no code change. It's endemic in E2E, and the default answer ("add a retry") hides the problem instead of fixing it.
To show it, I built a local page with a "Confirmar pedido" (confirm order) button whose toast appears between 0.5 and 2 seconds after the click, like a real API under load. First, the version that bets on a fixed time:
test('confirms the order (flaky)', async ({ page }) => {
await new LoginPage(page).login(user);
await page.getByRole('button', { name: 'Confirmar pedido' }).click();
await page.waitForTimeout(1000);
expect(await page.getByRole('status').textContent()).toBe('Pedido confirmado');
});
The Playwright documentation is blunt about waitForTimeout: never wait for timeout in production, tests that wait for time are inherently flaky; use locator actions and web-first assertions, which wait automatically. And page.waitForSelector, which many tutorials still recommend as the fix, is also marked as discouraged in favor of the same assertions. The correct version:
test('confirms the order', async ({ page }) => {
await new LoginPage(page).login(user);
await page.getByRole('button', { name: 'Confirmar pedido' }).click();
// web-first assertion: retries until the text shows up (default: 5 s)
await expect(page.getByRole('status')).toHaveText('Pedido confirmado');
});
I ran both with @playwright/test 1.64 on the official mcr.microsoft.com/playwright image, ten repetitions each (--repeat-each=10): the web-first assertion version passed 10 out of 10; the waitForTimeout version failed 5 out of 10. With --retries=2, the bad version became "6 flaky, 1 failed, 3 passed": retry hid most of the failures and still didn't save all of them.
Retrying in CI isn't forbidden; Playwright's own suggested config enables retries on CI. The difference is what you do with the result. The report separates "flaky" tests (failed, then passed on retry) from "passed" ones; treat every flaky test as an open bug, not as green. To diagnose, turn on trace: 'retain-on-failure' (or 'on-first-retry') and open the file with npx playwright show-trace: you see every action, the DOM and the network at the moment of failure.
Other common causes of flakiness:
Race conditions in async operations. The test clicks "Save" and checks the result immediately, before the API responds. The fix is the same: assert the expected state with expect and let Playwright wait.
Data shared between tests. Two tests that read and write the same record will step on each other when run in parallel. Each test creates its own data.
Dependence on external services. An E2E test that calls Stripe or a real email provider imports their instability into your pipeline. Use the provider's sandbox or intercept the call with page.route.
The rule I adopted: if a test went flaky more than twice in two weeks, it gets fixed or deleted. A test you don't trust is worse than no test, because it will fool you at the worst moment.
The maintenance cost nobody budgets for
Writing an E2E test is a maintenance commitment. The UI changes: the selector that was #submit-btn became something else, login gained a 2FA step, checkout was redesigned. Each change breaks some E2E test, not because the product is wrong, but because the test was coupled to the implementation.
The antidote is writing against visible behavior. getByRole('button', { name: 'Confirmar pedido' }) survives CSS and ID refactors; #btn-x93 doesn't. The user doesn't know the button's ID, they know what it says. On the example page, the button has exactly that kind of meaningless ID, and the test never notices it.
The other practice is the Page Object Model: instead of repeating the login steps in ten tests, one class holds the locators and actions. When the screen changes, you change one place:
export class LoginPage {
constructor(page) {
this.page = page;
this.email = page.getByLabel('E-mail');
this.password = page.getByLabel('Senha');
this.submit = page.getByRole('button', { name: 'Entrar' });
}
async login(user) {
await this.page.goto('/');
await this.email.fill(user.email);
await this.password.fill(user.password);
await this.submit.click();
await expect(this.page.getByRole('heading', { name: 'Carrinho' })).toBeVisible();
}
}
Note that the page object itself ends with a web-first assertion: login is only "done" when the next screen is visible, which removes one more source of race conditions.
Frequently asked questions
Should E2E tests run on every PR or only on merge?
It depends on suite time. If the full suite runs in a few minutes, run it on every PR. If it's much slower, many teams run a subset of critical flows on the PR and the full suite before merging to the main branch. What doesn't work is running everything on every commit of a long-lived branch: dozens of runs a day on code that is still changing.
Cypress or Playwright in 2026?
For a new project, I start with Playwright: several browsers (Chromium, Firefox and WebKit) in the same runner, per-context isolation, web-first assertions and the trace viewer. npm downloads point the same way: in the week of November 1 to 7, 2026, @playwright/test had about 115.7 million downloads against 7.7 million for cypress; in January 2024 the order was reversed (2.4 million against 4.5 million). Downloads count CI installs, not people, so treat it as a trend signal, not a scoreboard. If you already have a stable Cypress suite, there's no reason to migrate just for this.
Should you mock the backend in E2E tests?
Partially. Mocking the whole backend turns the E2E test into an expensive UI test: you verify the frontend renders data you made up. It makes sense to intercept third-party services (payments, email, SMS) and error responses that are hard to trigger. The difference between kinds of test doubles is in mock, stub, fake and spy.
How do you avoid logging in again in every E2E test?
With Playwright's storageState: a setup project logs in once, saves cookies and local storage to a file, and the other projects load it. The authentication docs recommend keeping that file in playwright/.auth and adding the folder to .gitignore, because it contains cookies that can be used to impersonate the test account.
E2E is at the top because it's expensive, not because it's best
E2E tests sit at the top of the pyramid because of cost, not merit. They pay off for flows where regression risk is high and the interaction between parts is exactly what you need to test: login, checkout, onboarding. For everything else, unit, integration and contract tests do the job better and cheaper. Write the few that remain with role and text locators, web-first assertions and zero waitForTimeout, and treat every test marked flaky as a bug. When a test fails only in CI, comparing the log of the red run with a green one in the Text Diff Checker usually shows the diverging line in seconds.
- 01 CPU Cores vs. Threads: What Actually Changes in Practice Understand the difference between CPU cores and threads and what actually changes for performance, multitasking, gaming, and development.
- 02 MIT, Apache, and GPL Licenses: Practical Differences for Developers MIT, Apache 2.0, and GPL are not the same thing. Understand permissive vs copyleft, patent protection, and compatibility before shipping code to production.