FE8: Unit and component tests

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

Faking the network and time

๐ŸŽฏYou'll be able to

Fake the network and the clock so tests are quick and repeatable.

๐Ÿ The everyday picture

A flight simulator lets pilots practise engine failures and storms safely on the ground. Fake servers and clocks let your tests practise slow networks, errors and timeouts without waiting for real ones.

๐Ÿ“˜What it really is

server.use(
  http.get('/api/stock', () => HttpResponse.json({ error: 'busy' }, { status: 503 }))
);

๐Ÿ“A worked example

Kirana's stock display tests with MSW:

Fake response Expected screen
Normal stock list Stock numbers next to products
[] (no products) "Nothing in stock at this store right now"
503 error "Couldn't load stock" with a "Try again" button that refetches
Kothrud slow (1 s), Baner fast (100 ms), customer switches to Baner Baner's stock only

The fourth test confirmed the abort logic from FE1 still works after moving to the caching library in FE2.

๐ŸŒWhere it's used

๐Ÿ“Case scenario

A team's tests pass, but in production an API error leaves customers staring at a spinner forever. No test covered the error state. Adding an MSW handler that returns a 500, and a test expecting an error message and retry button, shows the bug; the fix adds proper error handling.

๐Ÿ–ฑ๏ธTry it

Set up MSW for your Kirana stock API and write tests for loading, success, empty, error and out-of-order responses. Use fake timers to test an OTP countdown that enables "Resend" after 30 seconds.

โš ๏ธCommon mistakes

๐Ÿ› ๏ธFor your project

The kit's lib/fake-api.ts accepts test card 4111 1111 1111 1111 and declines 4000 0000 0000 0002; use them in Project 2.

โœ…Quick check

Why shouldn't tests call real APIs?

Show the answer

They'd be slow and unreliable, and could change real data.

Name four states a data-loading screen should be tested in.

Show the answer

Loading, success, empty and error (plus slow or out-of-order responses).

โ† PreviousComponent tests that act like users
ProLearners Assist