Search code examples
node.jsexpressmongoosejestjssupertest

Jest testing multiple test file port 3000 already in use


I'm creating a testing for my express app. The project has multiple test files. In each module the server instance is required at beforeEach() method and closed at afterEach() method. but after testing one or two of the modules it'll raise address already in use and jest won't terminate.

beforeEach(() =>  {

    server = require('./../../../bin/www')});
afterEach(async() => { 
    server.close();
    /**
     * database cleanup logic goes here.
     */

 });

I want jest to terminate after all the test suites are completed.


Solution

  • I had this issue, and seem to have solved it by setting jest to only use one worker. I think the issue was caused by more than one instance of the server running with the same port, thereby causing the clash.

    This is the line from my npm package.json file. The --maxWorkers=1 seems to have done the trick (https://jestjs.io/docs/en/cli#maxworkers-num-string).

    "scripts": {
      "test": "jest --forceExit --detectOpenHandles  --watchAll --maxWorkers=1"
    },