Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!