Part 10 / Topic 8 of 8
Testing a reducer in isolation
cartReducer is a plain JavaScript function - nothing about it needs a rendered component, a browser, or even React itself to test. examples/02_cart_reducer_pure.test.jsx never imports render or screen:
// examples/02_cart_reducer_pure.test.jsx
it("really adds a new dish with quantity 1, leaving the original state untouched", () => {
const next = cartReducer(initialCart, { type: "add", dish: paneerButterMasala });
expect(next.items).toEqual([{ ...paneerButterMasala, quantity: 1 }]);
expect(initialCart.items).toEqual([]);
});
This is the single biggest practical reason to reach for a reducer over several useState calls once an update gets complicated: the update logic itself is extracted far enough from rendering that it can be called directly, with plain objects in and a plain object out, and checked against exactly the same inputs every time - no render(), no userEvent, no DOM at all.
Done here? The practice set for Part 10 — including the solutions — is on the part page.