0

This is my query:

 getMyQuery: builder.query<bodyType, paramsType>({
          query: (qParams) => ({
            url: `url/endpoint`,
            method: 'POST',
            dataType: 'json',
            headers: {
              'Content-Type': 'application/json',
            },
            body: new URLSearchParams(paramsType as Record<string, string>),
          }),

It is working fine in my app. This is now how I mocked it with the test:

rest.get('url/endpoint', (req, res, ctx) => {
    console.log('req: ', req);
    return res(
      ctx.status(200),
      ctx.json({
        message: 'everything is fine',
        status: 'success',
      })
    );
  }),

and its output:

req:  {
      id: '5d761e1f-167e-4fb5-9ba7-6c950f186f62',
      url: URL {},
      method: 'POST',
      body: URLSearchParams {},
      credentials: 'include',
      headers: HeadersPolyfill {
        headers: {
          'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        names: Map(1) { 'content-type' => 'content-type' }
      },
      cookies: {},
      redirect: 'manual',
      referrer: '',
      keepalive: false,
      cache: 'default',
      mode: 'cors',
      referrerPolicy: 'no-referrer',
      integrity: '',
      destination: 'document',
      bodyUsed: false,
      passthrough: [Function: passthrough],
      params: [Object: null prototype] {}
    }

req.body is always empty.

I'm sending the Content-Type as it's described here in this other answer: Getting request body of mock service worker and react testing library

How could I get the entire body?

Dani
  • 3,128
  • 2
  • 43
  • 91

1 Answers1

0

The problem wasn't related with any of the libraries, just with the way I get the params from the URLSearchParams:

rest.get('url/endpoint', (req: { body: URLSearchParams }, res, ctx) => {
    console.log('req: ', req?.body.get('propName'));

More info: https://medium.com/swlh/urlsearchparams-in-javascript-df524f705317

Dani
  • 3,128
  • 2
  • 43
  • 91