Search code examples
node.jsexpressvitesteconnrefused

ECONNREFUSED error during testing with Vitest 0.32.0 + Node JS + Express


I'm experiencing a problem while running tests on my Express backend using Axios for making requests and Vitest for test execution. Here are the details:

  1. I have my backend running on localhost, port 3000, using Express.
  2. I am using Vitest for testing various endpoints that I have implemented.
  3. The issue arises when I add more test cases in my test files. Initially, when I run the tests for the first time, everything works fine.
  4. However, after adding more tests and saving them, my vitest tests restart (as expected) but throw the following error:
Serialized Error: Object {
"address": "::1",
"code": "ECONNREFUSED",
"config": Object {
"adapter": [Array],
"baseURL": "http://localhost:3000/api/users"
...

If I restart my Vitest server using my script for Vitest npm run test, the first test case works again, but the problem comes up again when I add more tests.

I have checked the Axios configuration, but everything seems to be in order. Additionally, if I make a fetch request to the endpoints from a file separate from my vitest test file customers.test.js, everything works normally.

Thanks in advance for any help you can offer!


Solution

  • After analyzing the issue more deeply, I noticed that whenever I added more tests and saved them, my server was also getting restarted. This was happening because I was using nodemon to watch for code changes. To fix this and continue using nodemon, you simply need to add the following configuration to your package.json file:

    {
      "name": "myName",
      "type": "module",
      ...
      "nodemonConfig": {
        "ignore": ["test/**/*.test.js"]
      }
    }
    

    In this case, you can replace "test/**/*.test.js" with whatever suits your needs. In my case, my tests are located in the "test/" directory, distributed in subfolders, and all the test files follow the "name.test.js" naming structure. There are other ways to add this configuration to nodemon, you can refer to the nodemon documentation at the nodemon documentation