Don’t have testing environment setup yet, but your frontend work requires consuming remote data from REST api?
No worries, in just a few simple steps, you can set up fully working REST API mock server.
Required tools
We are going to use Mock Service Worker for handling requests and faker to generate test data easily. I assume you have your frontend project setup already. I will show you integration with Create React App, but it is easy to apply in wide range of solutions.
First, let’s install required dependencies:
npm i -D msw @faker-js/faker
Let’s start with mocks
We are going to place out mocks inside:
mkdir src/mocks
I am using typescript, so for me request handlers will be placed inside:
touch src/mocks/handlers.ts
In my case I require paginated list to fill out my DataTable component, which is not within scope of this post.
import { rest } from 'msw'
/** Mock server handlers */
export const handlers = [
/** Fetch all users */
rest.get(`/api/users`, (req, res, ctx) => {
const responseContent = [
{
id: faker.datatype.uuid(),
name: faker.name.fullName(),
description: faker.lorem.text(),
updated: faker.date.past().getTime(),
},
{
id: faker.datatype.uuid(),
name: faker.name.fullName(),
description: faker.lorem.text(),
updated: faker.date.past().getTime(),
},
];
return res(
ctx.status(200),
ctx.json({
content: responseContent,
size: responseContent.length,
totalElements: responseContent.length,
totalPages: 1,
pageable: {
pageNumber: 0,
pageSize: 1000,
},
})
);
}),
];
Init mock service worker
For browser request interceptor with our service worker, we have to initialize msw from CLI:
npx msw init public/ --save
Create server
We will place server creator inside:
touch src/mocks/server.ts
And then inside server.ts we will implement a worker:
import { handlers } from "./handlers";
import { setupWorker } from "msw";
export const worker = setupWorker(...handlers);
Start server for dev environment
Finally, to start mocking server all we need to do is:
import React from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";
// this makes sure, mocking is enabled only locally for developement
if (process.env.NODE_ENV === 'development') {
const { worker } = require('./mocks/server')
worker.start()
}
const root = createRoot(document.getElementById("root") as HTMLElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
If everything went as expected, after starting the project, you should see
[MSW] Mocking enabled.
inside browser console and receive your mocked data as a network response for /api/users GET.
Make sure data returned from faker is in a normalized format, expected for given response - msw might respond with “graceful 500” without any further explanation, meaning your data might be invalid. Do not expect a 400, like in a true REST API case.
Summary
See, we were able to set up a working development environment in just a few minutes!