How To Mock Rest APIs With MSWJS In React - Part 1/2
In this post, we'll be doing a mock /GET request
In this series of blog posts, we will see how we can mock our endpoints without having to wait for our backend engineers to complete their work (๐) using mswjs. Without a further a due, let's get started.
Setup
In this post, we will use create-react-app to get started. Run the following command in your command line.
yarn create-react-app msw-react
cd msw-react
yarn start
or
npx create-react-app msw-react
cd msw-react
npm start
Let's install msw
as a devDependency
yarn add msw -D
or
npm install msw --save-dev
Implementation
After setting up the create-react-app, now let's create a /mocks
folder under /src
so that we can manage all the mocking related things here. Now let's create 2 files, handlers.js
& browser.js
under /src/mocks/
We will be writing mock endpoint functions in the handler.js file.
Let's create a function called getUserData()
which basically calls a /GET
endpoint with mock JSON data. This is how it looks like.
//src/mocks/handlers.js
import { rest } from "msw";
const mockUserData = {
name: "Mock Name",
email: "Mock Mail",
gender: "Mock Male",
address: "Mock Address"
};
// remember you have to match the params that you're passing here
const getUserData = rest.get("http://localhost:3000/users/1", (res, ctx) =>
res(ctx.json(mockUserData))
);
//it returns array of request handlers
export const handlers = [getUserData];
Now let's connect those handlers to the service worker, in browser.js file. This is how it looks like.
//src/mocks/browser.js
import { setupWorker } from "msw";
import { handlers } from "./handlers";
export const worker = setupWorker(...handlers);
Now let's call the mock service work in the index.js file, this is how it looks like
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";
//we can conditionally call this based on development or production, may be we can store an env or use NODE_ENV
const { worker } = require("./mocks/browser");
worker.start();
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<App />
</StrictMode>,
rootElement
);
That's it, finally, let's call the endpoint in our App.js file, and the code looks like this
import { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
const [user, setUser] = useState();
useEffect(() => {
const fetchUserData = async () => {
// remember we used /1 in our getUserData() handler
const res = await fetch("http://localhost:3000/users/1", {
method: "get"
});
const data = await res.json();
console.log(data);
setUser(data);
};
fetchUserData();
}, []);
return (
<div className={{marginTop: '20px'}}>
<h1>{JSON.stringify(user)}</h1>
</div>
);
}
Result
We can verify whether the mocking is enabled or not by looking into our browser console. We can see that the mock service worker got enabled and the data is present on the component as well.
Hurray..!!, that's it, we build our endpoint and consumed it without having to depend on our backend team ๐