1

I have a test in a react app that uses Mock Service Worker. I setup the server like this:

 const server = setupServer(

  // https://api.github.com/search/users?q=${userName}&type=users&per_page=10&page=${pageNo}`,
  rest.get('https://api.github.com/search/users/', async (req, res, ctx) => {
    console.log('rest req.params', req.params) // {} empty object
    console.log('rest req.url.searchParams', req.url.searchParams) // {} empty object
    const users = search_data[1]
    return res(ctx.json(users))
  }),

  // https://api.github.com/users/${user}
  rest.get(`https://api.github.com/users/:user`, async (req, res, ctx) => {
    // console.log('rest req.params.user', req.params.user) // this works as it should
    return res(
      ctx.json(
        users_data[1].users.find((user) => user.login === req.params.user)
      )
    )
  })
)

The first get request above is intercepting the the api endpoint which is commented out (the one above it). I am suppose to get the query parameters in an object, like the userName, but the returned object is empty. What am I doing wrong?

The intercepted code is the following:

const searchGithubApi = (
  userName: string,
  pageNo: number = 1,
  signal: AbortSignal
) => {
  console.log('userName', userName) // I get the correct userName
  return fetch(
    `https://api.github.com/search/users?q=${userName}&type=users&per_page=10&page=${pageNo}`,
    {
      headers: {
        Accept: 'application/vnd.github.v3+json',
      },
      signal,
    }
  ).then((res) => res.json())
}  

2 Answers2

3

You should use the URLSearchParams API to retrieve the request query parameter:

req.url.searchParams.get('q')

Logging out req.url.searchParams will always return an empty object, as you're effectively logging out a class instance that doesn't store query parameters as its properties (thus you see an empty object).

kettanaito
  • 974
  • 5
  • 12
1

See the link bellow, it explains it well. https://github.com/mswjs/msw/discussions/910