Mock service worker is unable to intercept network request

4.8k views Asked by At

I have a react project in this git repo created from scratch without using create-react-app, so I am using jest.config.js and jest.setup.js files as suggested by msw doc for mocking network request for testing. I get the below error when I executing the test.

(node:12207) ExperimentalWarning: The fs.promises API is experimental console.error Error: Error: connect ECONNREFUSED 127.0.0.1:5000

The same test code works fine when I create a new project using create-react-app containing setupTests.js, but I want to mock api request in a react project which was created manually from scratch.

Any suggestion?

1

There are 1 answers

1
somallg On

In the tutorial for msw, the mock server is configured in setupTests.js. Because CRA (create-react-app) already configure jest for you and CRA will load setupTests.js when you run test with react-scripts test.

If you want to create a new project from scratch (supposed you already installed react, react-dom, ... ).

You have to config jest your self (refer this docs), steps needed:

  1. Change test scripts in package.json to jest
  2. Install dependencies (babel, preset for jest, etc)
  3. Config jest with jest.config.js (like you did, i also add jsdom as test environment)
  4. Setup jest.setup.js to load mock server

I created a PR that did above steps for you, to test just run

npm run test App.test.js

Output:

enter image description here