Command Palette

Search for a command to run...

Hectal
Phase 17: Testing React
React · Exercise 5 of 5 Previous
Advanced

A tested cart: reducer, hook and UI

Write cartReducer(items, action) and the useCart() hook so the five given tests pass. Items look like { id, name, price, qty } (prices in paise).

Actions: { type: "added", item } adds the item with qty: 1, or raises qty by 1 if the same id is already there; { type: "removed", id } removes that item. The reducer must never change the old state. useCart() uses useReducer and returns { items, count, total, add(item), remove(id) }, where count is the sum of quantities and total the sum of price × qty.

Then add your own test whose name starts with my: and that uses renderHook to test remove.

The shop at the bottom must work: clicking Add Mango twice shows Total: ₹80.00 in #total.

What Check tests

  1. All five given tests pass
  2. No test fails
  3. Your own "my:" test uses renderHook and passes
  4. Clicking Add Mango twice shows Total: ₹80.00
  5. The cart uses useReducer

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.