How To Mock Rest APIs With MSWJS In React - Part 2/2
In this post, we'll be mocking /POST endpoint
If you've missed the first part of the series where we will be mocking endpoints with mswjs, please check out here.
/POST endpoint
Here in the /mocks/handlers.js
file, we will write a function called postUserData()
which basically mocks the posting of JSON data to a server. It looks something like this.
import { rest } from 'msw';
const mockUserData = {
name: 'Mock Name',
email: 'Mock Mail',
gender: 'Mock Male',
address: 'Mock Address'
};
const getUserData = rest.get('http://localhost:3000/users/1', (req, res, ctx) =>
res(ctx.json(mockUserData))
);
// /POST handler
const postUserData = rest.post('https://localhost:3000/users/1', (req,res,ctx) => {
const { name } = req.body
return res(
ctx.json({
name,
email: 'Mock Mail',
gender: 'Mock Male',
address: 'Mock Address'
})
)
})
// Do not forget to add the method in this array
export const handlers = [getUserData, postUserData];
Sending the data
First, let's just create a state for the user's name and data
const [name, setName] = useState('');
const [user, setUser] = useState(null);
Now let's create a simple input component using <form/>
and <input/>
tags & add appropriate event handler functions.
// input data event handler
const handleChange = (e) => {
setName(e.target.value);
}
// function to submit data
const handleSubmit = (e) => {
e.preventDefault();
}
<form onSubmit={handleSubmit}>
<input
name='name'
value={name}
onChange={handleChange}
placeholder='enter name'
/>
<br/>
<button type="submit">Submit Data</button>
</form>
Finally, let's call the endpoint after we click that Submit Data
button.
import { useState } from "react";
import "./styles.css";
export default function App() {
const [name, setName] = useState('');
const [user, setUser] = useState(null);
const handleChange = (e) => {
setName(e.target.value);
}
const postUserData = async () => {
const res = await fetch('http://localhost:3000/users/1', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({name}),
});
const data = await res.json();
setUser(data);
}
const handleSubmit = (e) => {
e.preventDefault();
postUserData();
}
return (
<div className={{marginTop: '20px'}}>
<h1>{ user ? JSON.stringify(user): 'no data'}</h1>
<form onSubmit={handleSubmit}>
<input
name="name"
value={name}
onChange={handleChange}
placeholder='enter name'
/>
<br/>
<button type="submit">Submit Data</button>
</form>
</div>
);
}
Now let's see it in action
And that's it we created our mock /POST
endpoint as well ๐, you can experiment with it by heading towards its documentation here at msw docs
ย