FE8: Unit and component tests

Lesson 2 of 5 ยท reading 15โ€“25 minutes; practice and project time is on the module page

Unit tests for logic

๐ŸŽฏYou'll be able to

Write unit tests for logic such as money formatting, including edge cases.

๐Ÿ The everyday picture

Before a big wedding feast, the cook tastes the masala on its own. If the spice blend is wrong, it's easier to catch now than after it's in fifty dishes.

๐Ÿ“˜What it really is

import { cartTotalPaise } from './cart';

test('applies free delivery at โ‚น499 and above', () => {
  const items = [{ pricePaise: 25000, qty: 2 }];          // โ‚น500
  expect(cartTotalPaise(items, { deliveryPaise: 3000 })).toBe(50000);
});

๐Ÿ“A worked example

Kirana's free-delivery rule: "Free delivery on orders of โ‚น499 or more; otherwise โ‚น30."

Cart value Expected total First result
โ‚น0 (empty) โ‚น0 (no delivery fee on empty cart) โ‚น30 โœ—
โ‚น498.99 โ‚น528.99 โœ“
โ‚น499.00 โ‚น499.00 โ‚น529.00 โœ— (used > instead of >=)
โ‚น1,200 โ‚น1,200 โœ“

Two bugs were found by edge-case tests before any customer saw them.

๐ŸŒWhere it's used

๐Ÿ“Case scenario

A customer reports being charged a delivery fee on a โ‚น499 order, though the banner says free delivery from โ‚น499. You write a test for exactly โ‚น499, see it fail, change > to >=, and keep the test so the bug can't quietly return.

๐Ÿ–ฑ๏ธTry it

Move your Kirana cart calculation into a plain function. Write at least eight tests covering empty cart, thresholds, offers and large quantities, using test.each for similar cases.

โš ๏ธCommon mistakes

๐Ÿ› ๏ธFor your project

lib/money.ts in the starter is broken on purpose; tests/unit/money.test.ts has 8 tests that pass once you fix it.

โœ…Quick check

What are the three parts of a unit test?

Show the answer

Arrange the data, act by calling the code, assert the result.

What should you do first when a bug is reported?

Show the answer

Write a test that reproduces it, then fix the code until the test passes.

โ† PreviousWhat to test, and how much
ProLearners Assist