Skip to main content

End-to-End and Automated Testing

Automated testing uses code to verify application behavior, while end-to-end testing checks a complete user journey across the real application.

Open the application
|
v
Perform user actions
|
v
Observe the visible result
|
v
Assert the expected behavior

One-line idea: Automation performs steps repeatedly; an E2E test performs a realistic journey and proves that the expected outcome occurred.

Core Concepts​

What Is Automated Testing?​

Automated testing means writing scripts that execute checks and validate results without requiring a person to repeat every step manually.

Automation can be used at every test level:

LevelExample automated check
UnitA price formatter returns the expected string
IntegrationSubmitting a form calls the API layer and displays the result
End-to-EndA user signs in, buys a product and sees confirmation

Automated testing provides:

  • repeatable checks
  • fast feedback after code changes
  • regression protection
  • consistent execution in CI pipelines
  • evidence such as logs, screenshots, traces and videos

Automation does not guarantee useful testing. The script must verify meaningful behavior.

Automation vs Testing​

An automation script only performs actions:

await page.goto("https://books.toscrape.com/");
await page.click(".nav-list li ul li a");

A test performs actions and validates an expected result:

const books = await page.$$(".product_pod");
assert(books.length > 0, "Expected at least one book");
Actions only             -> automation
Actions plus assertions -> automated test

A script that always finishes successfully can hide broken behavior. Assertions convert observed application state into a clear pass or failure.

What Is End-to-End Testing?​

End-to-End, or E2E, testing validates a complete workflow through the system from the user's point of view.

Browser UI
|
v
Frontend application
|
v
API and authentication
|
v
Database or service
|
v
Result shown in the browser

An E2E test can confirm that:

  • the application loads
  • controls are usable
  • requests reach the backend
  • authentication and authorization work
  • data is stored or retrieved correctly
  • navigation reaches the correct page
  • the final result is visible to the user

E2E tests give strong confidence in critical journeys because they cross real system boundaries. They are also slower and more expensive to maintain than focused unit or integration tests.

Choosing E2E Scenarios​

E2E suites should protect important user outcomes, not reproduce every unit-level condition through a browser.

Good E2E candidates include:

  • sign up, sign in and sign out
  • password recovery
  • search and filtering
  • checkout and payment confirmation
  • creating or editing important records
  • role-based access to protected pages
  • downloading or submitting important content

Prioritize scenarios by risk:

High business impact
+
High probability of regression
+
Difficult to validate at a lower level
|
v
Strong E2E candidate

Avoid creating a large browser test for every small validation branch. Put most detailed logic checks in unit and integration tests.

Anatomy of a Reliable E2E Test​

A clear E2E test usually follows four phases.

1. Arrange​

Prepare the user, data and application state.

Create a test user
Seed a known product
Start from a clean cart

2. Act​

Perform actions the way a user would.

Open product page
Add item to cart
Continue to checkout
Submit order

3. Assert​

Verify a user-visible outcome.

Confirmation heading is visible
Order number is displayed
Cart is empty

4. Clean Up​

Remove or reset data that could affect later tests when the environment does not isolate it automatically.

Delete created order
Reset feature flags
Revoke temporary user

Tests should remain independent. A test must not rely on another test running first.

Practical Playwright Example​

Playwright provides a browser automation API, test runner, assertions and debugging artifacts.

Install it in a project:

npm init playwright@latest

Example test:

import { test, expect } from "@playwright/test";

test("opens a book category and displays products", async ({ page }) => {
await page.goto("https://books.toscrape.com/");

await page.getByRole("link", { name: "Travel" }).click();

await expect(page).toHaveURL(/category\/books\/travel/);
await expect(page.getByRole("heading", { name: "Travel" })).toBeVisible();

const products = page.locator(".product_pod");
await expect(products).not.toHaveCount(0);
});

This test:

  1. opens the website
  2. clicks a category as a user would
  3. verifies navigation
  4. verifies the category heading
  5. verifies that products are displayed

Run it from the command line:

npx playwright test

Open the interactive UI while developing:

npx playwright test --ui

The exact command depends on the selected tool, but the testing pattern remains the same.

Puppeteer Example​

Puppeteer provides lower-level control of Chromium-based browsers. A standalone script can become a test by adding assertions and a failing exit path.

import assert from "node:assert/strict";
import puppeteer from "puppeteer";

const browser = await puppeteer.launch({ headless: true });

try {
const page = await browser.newPage();
await page.goto("https://books.toscrape.com/", {
waitUntil: "domcontentloaded",
});

await page.locator(".nav-list li ul li a").click();
await page.waitForSelector(".product_pod");

const bookCount = await page.$$eval(
".product_pod",
(cards) => cards.length,
);

assert(bookCount > 0, "Expected at least one book");
console.log("E2E test passed");
} finally {
await browser.close();
}

For a larger suite, use a test runner so failures, retries, parallel workers, reports and lifecycle hooks are managed consistently.

Selectors​

Selectors identify elements that a test will interact with.

Prefer selectors that reflect how users understand the interface:

page.getByRole("button", { name: "Place order" });
page.getByLabel("Email address");
page.getByText("Order confirmed");

Use a dedicated test identifier when an element has no stable semantic selector:

<button data-testid="checkout-submit">Place order</button>
page.getByTestId("checkout-submit");

Avoid fragile selectors tied to styling or DOM position:

.blue-button.mt-4
div:nth-child(3) > button
#generated-id-7392

A harmless layout change should not break a behavior test.

Waiting for the Application​

Browser applications update asynchronously. Tests must wait for meaningful conditions rather than guessing how long the application needs.

Avoid fixed sleeps:

await page.waitForTimeout(3000);

Prefer condition-based waits and assertions:

await expect(page.getByText("Order confirmed")).toBeVisible();
await expect(page).toHaveURL(/\/orders\/\d+/);

Modern E2E tools automatically wait for elements to become actionable and assertions to become true within a timeout.

Fixed wait
- always waits the full time
- still fails when the app is slower

Condition-based wait
- continues as soon as the condition is true
- clearly describes what the test needs

Do not increase every timeout to hide an unreliable test. Find the slow dependency, missing readiness condition or race.

Assertions​

An assertion compares the observed result with the expected behavior.

Useful E2E assertions include:

  • an element is visible or hidden
  • a button is enabled or disabled
  • text or an accessible name is correct
  • the URL matches the expected route
  • a table contains the created record
  • an error message appears for invalid input
  • a download is started
  • a network response has the expected outcome

Prefer user-visible results over implementation details.

await expect(page.getByText("Profile updated")).toBeVisible();

This is usually stronger than checking whether an internal React state value changed.

Test Data and Isolation​

Shared or unpredictable data is a common source of flaky tests.

Each test should start from a known state using one or more of these approaches:

  • seed a dedicated test database
  • create data through an API before the browser flow
  • generate unique user names or identifiers
  • reset changed records after the test
  • use isolated accounts or environments
  • mock only dependencies that are intentionally outside the test boundary
Known starting state
|
v
One independent test
|
v
Known final or cleaned state

Avoid depending on production data, test execution order or records manually created by a developer.

Real Backend or Mocked Backend?​

ApproachStrengthLimitation
Real backendValidates the complete systemSlower and requires controlled infrastructure
Mocked external dependencyFaster and deterministicDoes not validate that external integration
HybridKeeps owned services real and isolates unstable third partiesRequires a clearly documented boundary

An E2E test should use real components for the journey it claims to validate. Mocking the payment provider can be reasonable when the goal is to validate the application's checkout behavior against a known provider response.

Headless and Headful Execution​

Headless Mode​

The browser runs without a visible window.

const browser = await puppeteer.launch({ headless: true });

Use headless mode for:

  • CI pipelines
  • scheduled test runs
  • automation servers
  • normal regression suites

Headful Mode​

The browser window is visible.

const browser = await puppeteer.launch({ headless: false });

Use headful mode for:

  • developing a new test
  • watching the interaction sequence
  • debugging selectors and timing
  • reproducing a local failure
Develop and debug -> headful or interactive mode
Routine CI run -> headless mode

Headless and headful runs should represent the same browser behavior, but it is still useful to test supported browsers and viewport sizes explicitly.

Testing Pyramid​

The testing pyramid recommends many focused tests and fewer broad E2E tests.

              / E2E \
/-------\
/ Integration \
/---------------\
/ Unit \
/-------------------\
LevelQuantitySpeedMain purpose
UnitManyFastVerify isolated logic
IntegrationModerateMediumVerify connected parts
E2EFocused setSlowestVerify critical complete journeys

The exact shape can vary by application. The main principle is to test behavior at the lowest level that gives useful confidence, then reserve E2E coverage for high-value flows and system boundaries.

CI Pipeline Strategy​

Automated tests are most useful when they run consistently for code changes.

Developer opens pull request
|
v
Lint and unit tests
|
v
Integration tests
|
v
Critical E2E tests
|
v
Build or deployment decision

A practical pipeline can use:

  • Pull request: fast smoke tests for critical paths
  • Main branch: broader browser and feature coverage
  • Scheduled run: full suite across supported browsers
  • Post-deployment: a small production smoke or synthetic monitoring suite

Run independent tests in parallel when infrastructure and test data support it. Do not parallelize tests that mutate the same shared account or record.

Scheduled Tests and Production Monitoring​

Some browser flows can run on a schedule to detect production failures.

Scheduler starts a synthetic journey
|
v
Test checks login or another critical flow
|
v
Result is recorded
|
v
Failure triggers an alert

Production checks must be carefully designed:

  • use dedicated synthetic accounts
  • avoid real charges, messages or destructive actions
  • clean up generated data
  • protect credentials
  • respect rate limits
  • distinguish product failures from monitoring failures

Scheduled monitoring complements CI testing; it does not replace pre-deployment checks.

Failure Evidence and Debugging​

A useful failure should answer what failed, where it failed and what the application looked like.

Capture:

  • test name and error message
  • screenshot
  • execution trace
  • browser console errors
  • relevant network failures
  • video when useful
  • browser, operating system and build information
Test fails
|- assertion and stack trace
|- screenshot
|- browser trace
`- logs and network evidence

Avoid storing passwords, tokens or sensitive user data in test artifacts.

Flaky Tests​

A flaky test sometimes passes and sometimes fails without a meaningful application change.

Common causes include:

  • fixed time delays
  • unstable selectors
  • shared test data
  • dependence on test order
  • slow or unavailable third-party services
  • animations or unfinished network requests
  • environment resource shortages
  • leaked browser or application state

Retries can reveal intermittent failures, but they do not fix the cause.

When a test flakes:

  1. preserve its trace, logs and screenshot
  2. reproduce it under the same environment
  3. find the race, state leak or unstable dependency
  4. correct the test or application
  5. quarantine it only temporarily and assign ownership

Track flaky-test frequency so unreliable checks do not become accepted background noise.

Tool Comparison​

ToolMain strengthsGood fit
PlaywrightMulti-browser runner, auto-waiting, tracing, parallel executionModern web E2E suites
CypressInteractive runner, browser-focused debugging, built-in assertionsFrontend-heavy applications
PuppeteerDirect Chromium automation and lower-level controlCustom automation and focused browser scripts
SeleniumMature WebDriver ecosystem and broad language supportCross-language or established cross-browser suites

Tool choice matters less than test design. A reliable suite needs clear assertions, stable selectors, isolated data and useful failure evidence regardless of framework.

Common Mistakes​

MistakeBetter approach
Performing actions without assertionsValidate a meaningful user-visible result
Testing every edge case through the browserKeep most detailed logic in unit and integration tests
Selecting elements by CSS layoutPrefer role, label, text or stable test identifiers
Adding fixed sleepsWait for a specific UI or network condition
Sharing one account across parallel testsCreate isolated users and data
Depending on test orderMake every test independently runnable
Catching an error without failing the testLet the runner record a real failure
Using retries as the only flaky-test fixInvestigate and remove the underlying race or dependency
Running only in one browser when several are supportedTest a deliberate browser matrix
Saving no failure artifactsCapture screenshots, traces and useful logs
Using production data in CIUse a controlled test environment and synthetic records
Building only E2E testsBalance them with faster unit and integration coverage

Summary​

Automated testing repeatedly verifies behavior, while E2E testing validates complete user journeys through the running system.

Choose a critical user outcome
|
v
Prepare isolated and predictable data
|
v
Interact through stable user-facing selectors
|
v
Wait for meaningful application conditions
|
v
Assert the visible result
|
v
Capture failure evidence in CI
|
v
Fix flaky tests instead of normalizing them

A strong E2E suite is small enough to remain fast and maintainable, but broad enough to prove that the application's most important journeys work from the user's perspective.