Last Tuesday was the breaking point. A simple pull request to update a discount function caused a catastrophic cascade. The login failed. The cart emptied. The CEO’s test account showed a total price of . The company had to pay customers to buy things.
"You write the test first ," Mosh explained. "You watch it fail. Then you write just enough code to pass. This forces you to ask: What do I actually need? "
test('apply 20% discount to VIP users', () => { const user = { type: 'VIP' }; const total = 100; const result = applyDiscount(user, total); expect(result).toBe(80); }); He ran it. The function didn't exist yet.
test('calculate total price for two items', () => { // Arrange const cart = [{ price: 10 }, { price: 20 }]; // Act const result = calculateTotal(cart); // Assert expect(result).toBe(30); }); Leo typed along. For the first time, he ran npm test and saw that beautiful green checkmark. Passed. -Code With Mosh- Mastering JavaScript Unit Testing
He felt a strange rush. It wasn't the dopamine hit of shipping messy code fast. It was the quiet confidence of building a brick wall, one perfect brick at a time. The hardest chapter was Mocks & Stubs . Leo had an API call to fetchUserPaymentMethod . In production, this called a slow database. In tests, it was a nightmare.
FAIL checkout.test.js ✕ calculateTax should add 8% sales tax (5ms) ✕ applyDiscount should not apply to non-VIP (2ms) The tests screamed instantly. The broken line was caught before it ever reached production.
His boss, Sarah, would inevitably Slack him: “Hey Leo, the checkout button broke again. Also, the user profile picture is showing up on the invoice page.” Last Tuesday was the breaking point
npm run test:coverage A terminal window filled with green dots. Then, he did something reckless.
Leo plugged in his laptop and opened the test suite.
Leo turned to Sarah. "I broke the code on purpose. The tests found it in 0.3 seconds." The cart emptied
He wrote his first failing test:
He opened checkout.js and deliberately deleted a single line—the tax calculation.