4

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?

MarioG8
  • 5,122
  • 4
  • 13
  • 29
Patrick Obafemi
  • 908
  • 2
  • 20
  • 42

1 Answers1

6

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: {
    // Adding this header is important so that "req.body"
    // is parsed into an object in your request handler.
    '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.

kettanaito
  • 974
  • 5
  • 12
  • 6
    `req.body()` is now deprecated, if your body has JSON data you can use `req.json()` ([docs](https://mswjs.io/docs/api/request)) – mariogl Nov 27 '22 at 18:48
  • the body looks empty for me and I added the Content-Type – Dani Feb 22 '23 at 16:35