Static API Mocks vs Dynamic Frontend Test Data
- Average speed
- km/h
- Result
- Finish time
- 50 min
- You entered
- Distance
- 10 km
- You entered
Static API mocks (fixed JSON files) stop being enough when your frontend tests need to verify behavior that depends on data variability, timing, or state changes. You need dynamic mocks when you must test error handling, loading states, pagination, race conditions, or interactions that depend on the content of the response.
Formula
The calculator above computes average pace and speed from a finish time and distance. The formulas are:
- Pace (min/km) = Finish time (min) ÷ Distance (km)
- Speed (km/h) = Distance (km) ÷ (Finish time (min) ÷ 60)
Where Finish time is in minutes, Distance is in kilometers, Pace is in minutes per kilometer, and Speed is in kilometers per hour. For miles, replace km with miles and the pace becomes min/mile.
Worked Example
Using the default values: finish time = 50 minutes, distance = 10 km.
- Pace = 50 ÷ 10 = 5.00 min/km
- Speed = 10 ÷ (50 ÷ 60) = 10 ÷ 0.8333 = 12.00 km/h
The calculator shows an average pace of 5.00 min/km and an average speed of 12.00 km/h.
When to Use Static Mocks
Static mocks are a single JSON file (or a small set) that the frontend fetches instead of hitting a real API. They are ideal for:
- Unit tests of a component that only needs to render data once.
- Storybook or visual regression testing where you want a fixed, reproducible state.
- Simple CRUD apps where the test doesn’t depend on the data’s content.
Static mocks are fast, simple, and require no extra libraries. You just point your fetch mock to a file and you’re done.
When Static Mocks Fail
Static mocks break down when the test needs to simulate behavior that a fixed file cannot express. Common triggers:
- Error responses: A static file always returns 200 OK. You need to test a 500 error, a network timeout, or a malformed payload.
- Loading states: You want to verify that a spinner appears before data arrives and disappears after. A static mock resolves instantly, so the loading state never shows.
- Pagination and filtering: The UI needs to request page 2 or filter results. A static file can’t change its content based on query parameters.
- State changes: After a POST, the UI expects the list to update. A static mock returns the same data every time, so you can’t test that the new item appears.
- Race conditions: You need to simulate two overlapping requests that resolve out of order. Static mocks can’t control timing.
Dynamic Mocking Approaches
When static files are insufficient, you have several options, each with trade-offs.
1. Mock Service Worker (MSW)
MSW intercepts network requests at the service worker level and lets you define handlers that behave like a real API. You can return different responses based on the request URL, method, or body. For example, you can return a 500 error for a specific endpoint, or delay a response to test loading states. MSW works in both browser and Node (for Jest/Vitest), and it doesn’t require changing your app’s fetch calls.
2. Custom Fetch Mock with Logic
If you’re using Jest, you can mock the global fetch with a function that inspects the request and returns a response accordingly. This is simple but can become messy for complex scenarios. Libraries like fetch-mock or nock (for Node) offer more structured ways to define route-based responses.
3. In-Memory Fake API
Build a small Express server or a Node script that serves dynamic data from an in-memory database. This is useful for integration tests where you want to verify the full request/response cycle. It’s heavier than MSW but gives you full control over state and timing.
4. Record-and-Replay with Dynamic Overrides
Tools like Polly.js record real API responses and replay them, but allow you to override specific parts. This is useful when you want realistic data but need to tweak certain fields for edge cases. However, it adds complexity and may require maintaining recorded fixtures.
How to Choose the Right Approach
Consider the following factors:
- Test type: Unit tests can often use simple static mocks. Component tests that involve loading/error states need dynamic mocks. End-to-end tests usually run against a real backend or a full mock server.
- Team familiarity: If your team already uses MSW for development, using it for tests reduces context switching.
- Maintenance overhead: Static mocks are easy to maintain but become brittle as the API evolves. Dynamic mocks require more code but are more resilient to changes.
- Realism vs. speed: A real backend is the most realistic but slow and flaky. A dynamic mock gives you control and speed.
Common Mistakes and Pitfalls
- Over-mocking: Mocking every API call makes tests pass even when the app is broken. Only mock the specific endpoints you need to isolate.
- Ignoring network errors: A test that never simulates a timeout or a 500 error will miss important UI states.
- Hard-coding response shapes: If your mock returns a fixed object, your test won’t catch changes in the API contract. Use factories or generators to create varied data.
- Forgetting to reset state: In tests, if you don’t reset your mock between tests, you can get cross-test contamination. Always clear handlers or reset the mock in
beforeEach.
Frequently Asked Questions
Can I use static mocks for testing error states?
Not easily. A static file always returns a 200 status with the same data. To test error states, you need a mock that can return a 500, a 404, or a network failure. You can sometimes create a separate static file that represents an error response, but you still need to configure your mock to return it with the correct status code.
What is the difference between MSW and a simple fetch mock?
MSW intercepts requests at the network level using a service worker, so it works with any fetch or XHR call without modifying your code. A simple fetch mock replaces the global fetch function, which is fine for unit tests but may not work if your code uses XMLHttpRequest or a library that bypasses fetch. MSW also allows you to use the same mock definitions in development and testing.
How do I test loading states without a real network delay?
You can make your mock return a promise that resolves after a delay. For example, in MSW you can use await delay(1000) in the handler. In a custom fetch mock, you can return new Promise(resolve => setTimeout(() => resolve(response), 1000)). Then your test can assert that the loading indicator appears before the data is rendered.
Is it worth using a mock server for unit tests?
For pure unit tests, a simple mock is usually sufficient. A mock server (like MSW) is more valuable for integration tests or when you want to test the interaction between multiple components that fetch data. It adds a bit of setup but can make tests more realistic and reduce duplication.
Can I use static mocks for pagination?
No, because a static file cannot change its content based on the page number. You would need to either create multiple static files (one per page) and switch based on the request, or use a dynamic mock that reads the query parameter and returns the appropriate slice of data. The latter is much simpler.
What is the best practice for mocking APIs in frontend tests?
Start with static mocks for simple rendering tests. When you need to test error handling, loading states, or state changes, switch to a dynamic mock like MSW. Keep your mocks centralized and well-documented. Avoid mocking everything; only mock what the test needs to isolate. And always reset your mocks between tests to avoid flaky results.
Related
Formula used
in t | Finish time | min | 50 | 0 in d | Distance | km | 10 | 0 out pace | Average pace | min/km | t / d | 2 out speed | Average speed | km/h | d / (t / 60) | 2
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.