Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 35 ยท Projects

Project: Test a Shopping Cart and Checkout

Test a cart and checkout end to end: stub the catalog API, check totals and coupons in cents, cover error states, and keep test data under control.

A shopping cart is the classic test target because it mixes everything that makes browser tests hard: data from an API, arithmetic that must be exact, rules (coupons, free shipping), and failure states (the catalog is down). If you can test a cart well, you can test most of the web.

In this project you will plan and write the tests for a small shop. You will stub the catalog request so the products never change, check money in whole cents, cover a coupon, free shipping and an error with a retry button, and decide how to keep test data tidy.

Cypress and Playwright cannot run on this site, so the real test code is read-only and written for an imaginary shop at /shop. The runnable examples are stand-ins in plain JavaScript: a small cart, a fake fetch router that behaves like page.route and cy.intercept, and a tiny test runner. They let you see the logic of each test run. Where a number appears in the text, it comes from a real run of the stand-in.

The plan

Before you write a single line, list the behaviors worth protecting. For this shop:

  1. The catalog loads from GET /api/products and shows three products.
  2. Adding products and changing quantities updates the subtotal, shipping, tax and total.
  3. A valid coupon lowers the total. An unknown coupon shows a message and changes nothing.
  4. An order over a threshold ships for free.
  5. When the catalog request fails, the page shows an error with a Retry button, and Retry recovers.
  6. The happy path from the first click to the order confirmation works once, end to end.

Notice how much of this is logic (items 2 to 4). Arithmetic is cheaper to test in a unit test, so the browser tests only need a few representative numbers. Use the browser for what only the browser can prove: the page renders what the logic says, the buttons are wired up, and failures are visible. This is the idea from Testing Strategy and the Test Pyramid.

flowchart LR
  A["Stubbed catalog<br/>fixed products"] --> B["Add to cart"]
  B --> C["Coupon and totals"]
  C --> D["Checkout"]
  D --> E["Confirmation"]
  A -.->|"500 error"| F["Error with Retry"]
  F -->|"Retry"| A

The journey under test, with the failure branch that returns to the start.

Stub the catalog

A real catalog changes: prices move, products sell out. A test that expects $2.50 for the pen would fail the day marketing changes the price. Stubbing the request gives the test a fixed catalog that only your test file controls.

TypeScript
// Playwright (read-only): cart.spec.ts
import { test, expect } from '@playwright/test';

const products = [
  { id: 'pen', name: 'Pen', cents: 250 },
  { id: 'ink', name: 'Ink', cents: 1000 },
  { id: 'pad', name: 'Notebook', cents: 1200 },
];

test.beforeEach(async ({ page }) => {
  await page.route('**/api/products', (route) =>
    route.fulfill({ json: products }),
  );
  await page.goto('/shop');
});

test('shows the stubbed catalog', async ({ page }) => {
  await expect(page.getByTestId('product')).toHaveCount(3);
  await expect(page.getByTestId('product').first()).toContainText('Pen');
});

The same test in Cypress keeps the products in a fixture file, cypress/fixtures/products.json:

JavaScript
// Cypress (read-only): cypress/e2e/cart.cy.js
beforeEach(() => {
  cy.intercept('GET', '/api/products', { fixture: 'products.json' }).as('products')
  cy.visit('/shop')
  cy.wait('@products')
})

it('shows the stubbed catalog', () => {
  cy.get('[data-cy=product]').should('have.length', 3)
  cy.get('[data-cy=product]').first().should('contain', 'Pen')
})

Both versions register the stub before the page makes the request. If you register it after goto or visit, the real request has already left. The mechanics of both tools are covered in Intercepting and Mocking Network Requests.

Money in cents

Never assert on floating-point money. In JavaScript 0.1 + 0.2 is 0.30000000000000004, and a total built from decimals can drift by a cent. Store and compute prices as whole cents and format only at the edge. The stand-in below is a complete cart with a coupon table, free shipping above $50.00, and 8% tax. Run it first, then read how its tests map to browser tests.

JS A cart with coupons, and tests for it

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the second test. It checks every part of the total, not only the end. When a number is wrong, the failure message names the part (tax, shipping) instead of saying "total is wrong". The last test fails on purpose so you can see what a good failure message looks like.

In the browser, each of these becomes a short test that adds products with the real buttons and reads the real totals area:

TypeScript
// Playwright (read-only)
test('applies a coupon to the total', async ({ page }) => {
  await page.getByRole('button', { name: 'Add Pen to cart' }).click();
  await page.getByRole('button', { name: 'Add Pen to cart' }).click();
  await page.getByRole('button', { name: 'Add Ink to cart' }).click();

  await page.getByLabel('Coupon').fill('save10');
  await page.getByRole('button', { name: 'Apply' }).click();

  await expect(page.getByTestId('discount')).toHaveText('-$1.50');
  await expect(page.getByTestId('total')).toHaveText('$19.57');
});
JavaScript
// Cypress (read-only)
it('rejects an unknown coupon', () => {
  cy.contains('button', 'Add Notebook to cart').click()
  cy.get('[data-cy=coupon]').type('NOPE')
  cy.contains('button', 'Apply').click()
  cy.get('[data-cy=coupon-message]').should('have.text', 'Coupon not found')
  cy.get('[data-cy=total]').should('have.text', '$17.95')
})

Keep these in the browser suite as a handful, not dozens. The unit-level test above already covers the many combinations.

Error states

A page that works only when everything goes right is not finished. The most common failure here is the catalog request. Your tests should prove three things: the failure is visible, nothing crashes, and Retry works. Stubbing makes the failure easy to produce, because you cannot make a real server fail on demand.

TypeScript
// Playwright (read-only)
test('shows an error and recovers on retry', async ({ page }) => {
  let calls = 0;
  await page.route('**/api/products', (route) => {
    calls += 1;
    return calls === 1
      ? route.fulfill({ status: 500, json: { error: 'down' } })
      : route.fulfill({ json: products });
  });

  await page.goto('/shop');
  await expect(page.getByRole('alert')).toContainText('could not load');

  await page.getByRole('button', { name: 'Retry' }).click();
  await expect(page.getByTestId('product')).toHaveCount(3);
});
JavaScript
// Cypress (read-only)
it('shows an error and recovers on retry', () => {
  cy.intercept('GET', '/api/products', { fixture: 'products.json' })
  cy.intercept('GET', '/api/products', {
    times: 1,
    statusCode: 500,
    body: { error: 'down' },
  })

  cy.visit('/shop')
  cy.get('[role=alert]').should('contain', 'could not load')
  cy.contains('button', 'Retry').click()
  cy.get('[data-cy=product]').should('have.length', 3)
})

In Cypress the newest matching cy.intercept runs first, so the failing handler (limited to one use by times: 1) is registered after the healthy one. Once it is used up, requests fall through to the fixture.

The stand-in below models this with a fake fetch router, so you can watch the page states change: loading, error, then ready.

JS A storefront that survives a failing API

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real here, and what is not? The route table, the "newest first" order and the counter are the same ideas as the real tools. The page object is invented: in a real run the browser calls the application's own JavaScript, and the tool intercepts at the network layer.

Checkout and test data

Checkout is where you spend a real order, so treat it carefully.

  • Never hit a real payment provider. Use the provider's test mode, or stub POST /api/orders and assert on the request body (items, coupon, totals) as well as on the confirmation message.
  • Make the order data unique per run. If the shop rejects duplicate emails or reuses order numbers, generate the email in the test: `buyer+${Date.now()}@example.com`. Unique data lets tests run in parallel without colliding.
  • Don't depend on previous tests. Each test builds its own cart. If the cart lives in localStorage, both tools start every test with a clean browser context or fresh session state, so a test never inherits the last one's cart.
  • One full journey. Keep a single test that goes catalog, cart, coupon, checkout and confirmation using the real UI, and let the others skip ahead by seeding. Test Data and Logging In Fast shows how.

A good order stub also checks what the page sent:

TypeScript
// Playwright (read-only)
test('submits the order with the right totals', async ({ page }) => {
  let body: any;
  await page.route('**/api/orders', async (route) => {
    body = route.request().postDataJSON();
    await route.fulfill({ status: 201, json: { id: 'ord_1' } });
  });

  // ...add products, apply SAVE10, fill the address...
  await page.getByRole('button', { name: 'Place order' }).click();

  await expect(page.getByRole('heading', { name: 'Thank you' })).toBeVisible();
  expect(body.coupon).toBe('SAVE10');
  expect(body.items).toEqual([{ id: 'pen', qty: 2 }, { id: 'ink', qty: 1 }]);
});

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should cart tests compute and compare money in whole cents?

    Binary floating point cannot represent values like 0.1 exactly. Integer cents avoid rounding surprises, and you format to dollars only for display.
  2. 2. Why register a route stub before visiting the page?

    The catalog request leaves while the page loads. A stub must already be in place to answer it.
  3. 3. Which test is most worth running in the browser rather than as a unit test?

    Arithmetic is cheap to cover in unit tests. The browser proves wiring and visible behavior, such as an error state the user can recover from.
  4. 4. In the Cypress example, why is the failing intercept registered after the healthy one?

    Cypress matches the most recently defined handler first. With times: 1 it is used once, then the earlier fixture handler answers.
  5. 5. How do you keep checkout tests from colliding when they run in parallel?

    Unique, independent data lets many tests run at once without affecting each other.

Summary

  • List the behaviors first; keep arithmetic in unit tests and use the browser for wiring and visible states.
  • Stub the catalog before navigation so products and prices never change under your test.
  • Work in whole cents and assert on each part of the total, so failures name the broken part.
  • Test error states on purpose: a stubbed 500, a visible alert and a Retry that recovers.
  • Stub the order endpoint and assert on what the page sent, not only on what it shows.
  • Make test data unique and each test independent, and keep one real end-to-end journey.

Next: Project: Combine API Setup with UI Checks