Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 30 ยท Projects

Project: Test a Shopping Cart

Build and test a shopping cart module test-first with Jest: red-green-refactor, edge cases, a mocked price API and clear failure messages, with runnable stand-ins.

In this project you will build a small shopping cart the way many professional teams do: by writing the tests first. You will add one behavior at a time, watch a test fail, make it pass, and tidy up. By the end you will have a cart with quantities, a coupon, and a total that depends on prices fetched from an API, which your tests replace with a mock.

Everything you need has appeared earlier in the course: matchers from Common Matchers, mock functions from Mock Functions with jest.fn, and async tests from Testing Promises and Async/Await. This lesson is about combining them.

Real versus stand-in. The Jest test files in this lesson are real and read-only, because the site cannot run the jest package. The TryIt blocks run the same cart and the same checks on Node.js with a ten-line test runner, a tiny expect and a hand-made mock. They are stand-ins: copy the logic into a Jest project to run it for real.

Red, green, refactor

Red Write a test that fails.
Green Write the least code that passes.
Refactor Clean up while tests stay green.

Small steps keep every failure easy to explain.

1 / 2

The plan

We will write cart.js exporting createCart(priceApi). The price API is passed in (dependency injection, as in Mocking Modules), so the cart never needs the network. A price API is any object with an async getPrice(sku) that returns a price in cents, or null when the product is unknown. Prices in whole cents avoid the floating-point trouble covered in Numbers and Strings.

The behaviors, in the order we will build them:

  1. A new cart is empty.
  2. add(sku, quantity) puts items in; adding the same sku again increases the quantity.
  3. remove(sku) takes a product out.
  4. total() asks the API for prices and adds up price times quantity.
  5. applyCoupon("SAVE10") gives 10 percent off.
  6. Bad input and API failures produce clear errors and leave the cart unchanged.

Step 1: red

Start with the smallest test. In Jest it would be:

JavaScript
// cart.test.js
const { createCart } = require("./cart");

describe("cart lines", () => {
  test("a new cart is empty", () => {
    const cart = createCart({ getPrice: jest.fn() });
    expect(cart.itemCount()).toBe(0);
  });

  test("adding the same product twice increases its quantity", () => {
    const cart = createCart({ getPrice: jest.fn() });
    cart.add("apple", 2);
    cart.add("apple");
    expect(cart.quantityOf("apple")).toBe(3);
    expect(cart.itemCount()).toBe(3);
  });

  test("remove deletes the product", () => {
    const cart = createCart({ getPrice: jest.fn() });
    cart.add("apple", 2);
    cart.remove("apple");
    expect(cart.itemCount()).toBe(0);
  });
});

Running this before cart.js exists fails with "Cannot find module". That is the red step: a failing test proves the test can fail. Then you write just enough code to pass. The stand-in below shows both phases: first against a stub that does nothing (red), then against a real implementation (green).

Node.js Red, then green: the cart lines

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The stub passes two of the three tests by accident (an empty count is what it always reports), which is a nice reminder: a test that passes before you write any code is telling you little, so check that each new test fails first for the right reason.

Step 2: prices from a mocked API

The total needs prices, which come from the outside world. In the test we hand the cart a mock getPrice that returns known values, so the answer is predictable and no network is used:

JavaScript
describe("cart total", () => {
  const prices = { apple: 120, bread: 350 };
  let getPrice;
  let cart;

  beforeEach(() => {
    getPrice = jest.fn(async (sku) => prices[sku] ?? null);
    cart = createCart({ getPrice });
  });

  test("an empty cart totals zero without calling the API", async () => {
    expect(await cart.total()).toBe(0);
    expect(getPrice).not.toHaveBeenCalled();
  });

  test("multiplies price by quantity and adds the lines", async () => {
    cart.add("apple", 3);
    cart.add("bread");
    expect(await cart.total()).toBe(3 * 120 + 350);
  });

  test("looks up each product once", async () => {
    cart.add("apple", 5);
    await cart.total();
    expect(getPrice).toHaveBeenCalledTimes(1);
    expect(getPrice).toHaveBeenCalledWith("apple");
  });
});

Fresh mock and a fresh cart in beforeEach mean the tests cannot influence each other (see Setup and Teardown Hooks). The third test pins down a useful design rule: ask for the price of each distinct product once, not once per unit.

Step 3: coupons and edge cases

Edge cases are where a project earns its tests. Think about what a user, or a bug, could do:

  • Add zero, a negative number, 1.5, or a string as the quantity.
  • Ask for the total of a product the API does not know.
  • Have the API reject its promise because it is offline.
  • Apply a coupon that does not exist, or apply it twice.
  • Rounding: 10 percent off 995 cents is 99.5 cents.

Many of these share a shape, so a table fits (see Table-Driven Tests with test.each):

JavaScript
test.each([
  [0], [-1], [1.5], ["2"], [NaN],
])("add rejects quantity %p", (quantity) => {
  expect(() => cart.add("apple", quantity)).toThrow("quantity must be a positive whole number");
});

test("a failed price lookup rejects and keeps the cart intact", async () => {
  getPrice.mockRejectedValueOnce(new Error("offline"));
  cart.add("apple", 2);
  await expect(cart.total()).rejects.toThrow("offline");
  expect(cart.itemCount()).toBe(2);
});

Decide, and test, what the cart does with a fractional discount. Here we round to the nearest cent: a 995-cent cart with SAVE10 earns a discount of 99.5 cents, Math.round turns that into 100, and the total is 895 cents. Work such numbers out by hand before you write the expectation.

The stand-in now contains the complete cart, a hand-made mock with call tracking, and the edge-case checks.

Node.js The complete cart with a mocked price API

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Running the table of bad quantities produced five separate, named tests, so a failure points at the exact input. That is the same benefit test.each gives in Jest.

Step 4: refactor with confidence

Now the tests pay off. Two possible clean-ups:

  • Move the 0.1 into a named constant, or a table of coupon codes, so new coupons are a data change.
  • Fetch prices for all lines in parallel with Promise.all.

Make one change, run the suite, and watch it stay green. The tests describe the behavior (what total, how many API calls, which errors), not the implementation, so they let you restructure freely. If a refactor breaks a test even though the behavior did not change, that test was checking implementation details and is worth rewriting.

Ideas to extend the project

  • Add setQuantity(sku, quantity) where 0 removes the line.
  • Add FREESHIP as a second coupon type and decide how it combines with SAVE10.
  • Cache prices for the lifetime of the cart and test that a second total() does not call the API again.
  • Write a test using fake timers for a cart that expires after 30 minutes (see Mocking Timers, Dates and HTTP).
  • Run jest --coverage and look for branches you never exercised (see Coverage and Test Quality).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why watch a new test fail before writing the code?

    A test that has never failed might not be testing anything. Seeing it fail first confirms it detects the missing behavior.
  2. 2. Why does the cart receive priceApi as a parameter?

    Passing the dependency in lets the test supply a predictable fake, which keeps the test fast and deterministic.
  3. 3. Where should the fresh mock and fresh cart be created for each test?

    beforeEach rebuilds the state for every test, which prevents order-dependent failures.
  4. 4. A refactor keeps the cart's behavior the same but a test fails. What is the most likely reason?

    Tests should describe observable behavior. When they break on a harmless change, they are coupled to internals.

Summary

  • Test-driven development repeats red (a failing test), green (the least code that passes) and refactor (clean up while green).
  • Inject the price API so tests pass a mock and the cart never touches the network.
  • Store money in whole cents and decide, then test, how rounding works.
  • Edge cases (bad quantities, unknown products, API failures, unknown coupons) deserve their own named tests, and a table keeps them compact.
  • Good tests describe behavior, so they survive refactoring.

Next, build an HTTP client with retries and timeouts in Project: Test an API Client.