npm install -D vitest
Practice the Red-Green-Refactor cycle by building a ShoppingCart class test-first.
1 import { describe, it, expect } from 'vitest'; 2 import { ShoppingCart } from './cart'; 3 4 describe('ShoppingCart — TDD', () => { 5 // Red 1: empty cart 6 it('starts empty with zero total', () => { 7 const cart = new ShoppingCart(); 8 expect(cart.itemCount).toBe(0); 9 expect(cart.total).toBe(0); 10 }); 11 12 // Red 2: add item 13 it('adds item and updates total', () => { 14 const cart = new ShoppingCart(); 15 cart.add({ id: '1', name: 'Book', price: 29.99, qty: 2 }); 16 expect(cart.itemCount).toBe(1); 17 expect(cart.total).toBeCloseTo(59.98); 18 }); 19 20 // Red 3: remove item 21 it('removes item by id', () => { 22 const cart = new ShoppingCart(); 23 cart.add({ id: '1', name: 'Book', price: 10, qty: 1 }); 24 cart.add({ id: '2', name: 'Pen', price: 2, qty: 3 }); 25 cart.remove('1'); 26 expect(cart.itemCount).toBe(1); 27 expect(cart.total).toBeCloseTo(6); 28 }); 29 30 // Red 4: discount 31 it('applies percentage discount code', () => { 32 const cart = new ShoppingCart(); 33 cart.add({ id: '1', name: 'Shirt', price: 100, qty: 1 }); 34 cart.applyDiscount('SAVE20'); // 20% off 35 expect(cart.total).toBeCloseTo(80); 36 }); 37 38 // Red 5: invalid discount 39 it('ignores unknown discount codes', () => { 40 const cart = new ShoppingCart(); 41 cart.add({ id: '1', name: 'Hat', price: 30, qty: 1 }); 42 cart.applyDiscount('INVALID'); 43 expect(cart.total).toBeCloseTo(30); 44 }); 45 });
All cart behaviors driven by failing tests first: add, remove, discount, total
Sign in to share your feedback and join the discussion.