Inspecting Request Bodies in Handlers
You'll learn how to access and assert on POST/PUT request payloads inside MSW handlers to verify your forms are sending the right data.
When testing form submissions, it's not enough to verify the request happened—you need to confirm the form sent the correct data. MSW handlers give you full access to the request object, letting you inspect what your component actually sent to the "server."
The Core Idea
Inside an MSW handler, the request parameter contains methods to parse the body:
await request.json()— For JSON payloads (most APIs)await request.text()— For plain text or form-encoded data
You can use these in your handler to make assertions about what data the component sent. This is particularly valuable for testing forms, where user input should translate into specific API payloads.
How It Works
http.post('/api/users', async ({ request }) => {
const body = await request.json();
// Assert the form sent the right fields
expect(body.email).toBe('test@example.com');
expect(body.password).toHaveLength(8);
return HttpResponse.json({ id: 1, ...body });
})
Think of it like this: You're not just a mock server responding to requests—you're also an inspector examining what gets sent to you. It's like checking the ingredients someone put in a recipe before you hand back the finished dish.
This approach catches bugs where forms exist, events fire, and requests happen... but the data is malformed or missing fields.
Key Takeaway: Use await request.json() or await request.text() in MSW handlers to inspect and assert on request payloads, ensuring your forms send the exact data your API expects.