Add tests for the cart reducer

React · React · advanced · greenfield

Adds the missing test suite for the cart reducer: concrete-value assertions for every action type, a structuredClone-based purity check, clamp boundaries on both ends, and a same-reference assertion for unknown actions. The reducer itself is included unchanged for context.

Requirements

Files touched

--- src/state/cartReducer.js
+export const initialCart = { items: [], couponCode: null };
+
+export function cartReducer(state, action) {
+  switch (action.type) {
+    case 'add-item': {
+      const { productId, unitPriceCents } = action;
+      const existing = state.items.find((item) => item.productId === productId);
+      if (existing) {
+        return {
+          ...state,
+          items: state.items.map((item) =>
+            item.productId === productId ? { ...item, quantity: item.quantity + 1 } : item,
+          ),
+        };
+      }
+      return { ...state, items: [...state.items, { productId, unitPriceCents, quantity: 1 }] };
+    }
+    case 'set-quantity': {
+      const quantity = Math.max(1, Math.min(99, action.quantity));
+      return {
+        ...state,
+        items: state.items.map((item) =>
+          item.productId === action.productId ? { ...item, quantity } : item,
+        ),
+      };
+    }
+    case 'remove-item':
+      return {
+        ...state,

Review this PR

React practice