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
- Tests shouldn't call real APIs: they'd be slow, flaky and could change real data.
- Mock Service Worker (MSW) intercepts network requests and returns responses you define, at the network level, so your app's real fetching code runs.
server.use(
http.get('/api/stock', () => HttpResponse.json({ error: 'busy' }, { status: 503 }))
);
- Test every state a screen can be in:
- loading (a skeleton appears);
- success (data shows);
- empty (a helpful message);
- error (a clear message and a retry button);
-
slow responses and out-of-order responses (the race condition from FE1).
-
Fake timers (
vi.useFakeTimers()) let you jump time forward to test countdowns, debouncing and timeouts instantly. - Reset mocks between tests, so one test's fake response doesn't leak into the next.
๐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
- Any screen that loads data.
- Payment and OTP flows, with timers and failures.
- Search-as-you-type, with debouncing.
๐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
- Calling a real API in tests. Sign: tests fail when the network is slow. Fix: use the kit's fake API or MSW.
- Waiting with real time. Sign: a test sleeps for five seconds. Fix: use fake timers.
๐ ๏ธ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).
