Vitest + MSW - Runtime request handler is not working

1.3k views Asked by At

I'm trying to migrate the test framework of my app from Jest to Vitest (for multiple reasons) and I encounter an issue.

With Jest, I was using runtime request handlers at multiple places of my app to control that I have the correct behavior/output in my component regarding the response of the API call.

It was working well! But now, with Vitest, I can't achieve the same behavior.

I'm doing the same thing as before, calling server.use() to mock my response for a specific request inside my test, but MSW does not return the the response defined with the use method, but the one defined in my default handlers given when called setupServer().

For example, I am doing the following:

  it('should call the correct endpoint and return the API response', async () => {
    mockApiResponse({
      endpoint: `/companies/1/api-key`,
      method: RESTMethods.POST,
      response: MOCK_CREATE_COMPANY_API_KEY_API_RESPONSE,
      statusCode: 201,
    })

    const { result, waitFor } = renderHook(() => useCreateCompanyApiKey(1))
    result.current.mutate()
    await waitFor(() => result.current.isSuccess)
    expect(result.current.data).toEqual(MOCK_CREATE_COMPANY_API_KEY_API_RESPONSE)
  })

For the record, here's the implementation of my mockApiResponse method:

const mockApiResponse = ({
  endpoint = '*',
  method = RESTMethods.GET,
  response = {},
  statusCode = 200,
}: MockApiResponseArgs) => {
  switch (method) {
    case RESTMethods.DELETE:
      server.use(rest.delete(endpoint, (req, res, ctx) => res(ctx.status(statusCode), ctx.json(response))))
      break
    case RESTMethods.PATCH:
      server.use(rest.patch(endpoint, (req, res, ctx) => res(ctx.status(statusCode), ctx.json(response))))
      break
    case RESTMethods.POST:
      server.use(rest.post(endpoint, (req, res, ctx) => res(ctx.status(statusCode), ctx.json(response))))
      break
    case RESTMethods.PUT:
      server.use(rest.put(endpoint, (req, res, ctx) => res(ctx.status(statusCode), ctx.json(response))))
      break
    default:
      server.use(rest.get(endpoint, (req, res, ctx) => res(ctx.status(statusCode), ctx.json(response))))
      break
  }
}

And just so you know, my useCreateCompanyApiKey hook is a custom hook around the useMutation one from @tanstack/react-query

With this, code, with Jest, I have the test passing, with vitest, it won't has the response of the request won't be the value of MOCK_CREATE_COMPANY_API_KEY_API_RESPONSE ...

If anyone has an idea or has already encountered a similar issue, it can really help me! :)

0

There are 0 answers