How can I unit test a react app using msw for mocking?

362 views Asked by At

I'm trying to test a react app using msw to mock server responses and jest to run tests.

I want to access the dom so I need to use jsdom as a test environment. Any other environement (eg node) will get me this error :

The error below may be caused by using the wrong test environment, see     https://jestjs.io/docs/configuration#testenvironment-string.

Consider using the "jsdom" test environment. > ReferenceError: document is not defined

I can't use msw web workers in my jest unit tests because I get this error :

● Test suite failed to run

Invariant Violation: [MSW] Failed to execute setupWorker in a non-browser environment. Consider using setupServer for Node.js environment instead.

  2 | import { setupWorker } from 'msw/browser';
  3 |
  4 | export const worker = setupWorker(...handlers);

I can't use msw server mode because it is not supported by the jsdom env

● Test suite failed to run

Cannot find module 'msw/node' from 'src/tests/mocks/server.ts'

Require stack:
  src/tests/mocks/server.ts
  src/tests/setupTests.ts

  1 | import { handlers } from './handlers';
> 2 | import { setupServer } from 'msw/node';

I'm using msw 2.0.0 and jest 29.7.0

Any hint on how to get this to work ? Thank you !

0

There are 0 answers