'how to mock a post request with MSW in jest
I am new to testing and am currently trying to test a form from my svelte app. On this form there is only one input for a category. When the backend receives this category a uuid is generated for it and a json object with the category and uuid is returned.
it('submits info', async () => {
render(ItemsForm);
let requestBody;
const server = setupServer(
rest.post(`http://localhost:5025/api/categories`, (req, res, ctx) => {
requestBody = req.body;
return res(ctx.status(200), ctx.json({
name: 'Action',
}))
})
);
server.listen();
server.printHandlers()
const itemInput = screen.getByLabelText('Categories Name');
await userEvent.type(itemInput, 'Action')
const submitBTN = screen.queryByRole('button', {name: `Save Categories`})
await userEvent.click(submitBTN);
server.close();
expect(requestBody).toBe
({
name: 'Action',
})
})
when I run the test the error that i receive is
expect(received).toBe(expected) // Object.is equality
Expected: {"name": "Action"}
Received: undefined
64 | await userEvent.click(submitBTN);
65 | server.close();
> 66 | expect(requestBody).toBe
| ^
67 | ({
68 | name: 'Action',
69 |
I have tried various approaches and tried to search for online resources to find a solution but have not been able to make progress towards a solution.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|