Handling POST, PUT, DELETE Requests
What you'll learn: How to mock mutation endpoints (POST, PUT, DELETE) in MSW to test form submissions and data-changing operations in your React components.
Why Mutations Need Different Handlers
You've already seen http.get for queries. But real apps also change data—creating users, updating profiles, deleting posts. MSW provides http.post, http.put, and http.delete to intercept these mutation requests, letting you test the full user flow without a backend.
The Core Pattern
Each mutation handler follows the same structure as GET, but you'll typically:
- Read the request body (for POST/PUT)
- Return a success response with the created/updated resource
- Or simulate errors for edge cases
import { http, HttpResponse } from 'msw'
export const handlers = [
http.post('/api/users', async ({ request }) => {
const newUser = await request.json()
return HttpResponse.json({
id: '123',
...newUser,
createdAt: new Date().toISOString()
}, { status: 201 })
}),
http.put('/api/users/:id', async ({ params, request }) => {
const { id } = params
const updates = await request.json()
return HttpResponse.json({
id,
...updates,
updatedAt: new Date().toISOString()
})
}),
http.delete('/api/posts/:id', ({ params }) => {
return HttpResponse.json(null, { status: 204 })
})
]
Testing Form Submissions
With these handlers, you can test a complete form flow: fill inputs with user-event, submit, wait for success messages—all without a real server:
test('creates new user on form submit', async () => {
const user = userEvent.setup()
render(<CreateUserForm />)
await user.type(screen.getByLabelText(/name/i), 'Alice')
await user.click(screen.getByRole('button', { name: /submit/i }))
expect(await screen.findByText(/user created/i)).toBeInTheDocument()
})
Key Takeaway: Use http.post, http.put, and http.delete with resolvers that read request bodies and return appropriate status codes to test mutations exactly like real user workflows.