简体   繁体   中英

Getting request body of mock service worker and react testing library

So i am writing tests for one of my react projects and i just decided to use mock service worker to mock my api calls and i am trying to mock a login endpoint.So i am trying to simulate a login error where i return an error message when the input does not match a particular email. Given the code below;

const server = setupServer(
  rest.post("https://testlogin.com/api/v1/login", (req, res, ctx) => {
    // the issue is getting the email from the request body something like the code just below
    if (req.body["email"] != "test@example.com") {
      ctx.status(401);
      return res(
        ctx.json({
          success: false
        })
      );
    }
  })
);

How can i do that? Is there a better way to do that?

You should be able to get the req.body.email value given your request sets the Content-Type: application/json header . Without the Content-Type header, neither MSW nor your actual server could know what kind of data you're attempting to send (if anything, it can be a binary.). By providing the correct Content-Type header you form a correct request but also let MSW be sure that req.body should be parsed to an object.

// your-code.js
fetch('https://testlogin.com/api/v1/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ login: 'admin@site.com' })
})
// your-handlers.js
rest.post('https://testlogin.com/api/v1/login', (req, res, ctx) => {
  const { login } = req.body

  if (login !== 'test@example.com') {
    return res(ctx.status(401), ctx.json({ success: false }))
  }

  return res(ctx.json({ success: true }))
})

Note how the ctx.status(401) call is inside the res() function call. Calling any ctx[abc] methods outside of res will result in no effect as they rely on being wrapped in res .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM