'Jest TestEnvironment - TypeError: Cannot add property next, object is not extensible

I want to test a node API using Jest. I am testing the routes and websockets. Testing the routes was no problem. I simply started the server using the setupFile option.
To test the websockets I wanted to pass the io object to the tests. This is not possible through the setupFile since the tests are running in their own context. Thus I changed to the testEnvironment option. My testEnvironment file is the following

const NodeEnvironment = require('jest-environment-node');

class CustomEnvironment extends NodeEnvironment {
  constructor(config, context) {
    super(config, context);
    this.setupServer();
  }

  async setup() {
    await super.setup();
    console.log('Setup Test Environment.');
    this.global.io = this.io;
    this.global.baseUrl = 'http://localhost:' + this.port;
  }

  async teardown() {
    await super.teardown();
    console.log('Teardown Test Environment.');
  }

  getVmContext() {
    return super.getVmContext();
  }

  setupServer() {
    // Code for starting the server and attaching the io object
    this.port = portConfig.http;
    this.io = io;
  }
}

module.exports = CustomEnvironment;

This works and the io object is passed to the test. I have multiple test files for different parts of the API. Running those with the setupFile was no problem but now Jest is only able to run one file. All following test suites are failing with the following message

● Test suite failed to run

    TypeError: Cannot add property next, object is not extensible

      at Function.handle (node_modules/express/lib/router/index.js:160:12)
      at Function.handle (node_modules/express/lib/application.js:174:10)
      at new app (node_modules/express/lib/express.js:39:9)

I am not able to find any documentation on that error. I tried disabling some of the test files but it always fails after the first one, no matter which one it is.

The structure of the test files is the following if relevant:

const axios = require('axios');

describe('Test MODULE routes', () => {
  const baseUrl = global.baseUrl;
  const io = global.io;
  const models = require('../../../models'); // sequelize models which are used in tests

  describe('HTTP METHOD + ROUTE', () => {
    test('ROUTE DESCRIPTION', async () => {
      const response = await axios({
        method: 'get',
        url: baseUrl + 'ROUTE'
      });

      expect(response.status).toBe(200);
    });
  });

  // different routes
});



Solution 1:[1]

I fixed the error. It had nothing to do with jest but with an module.exports invocation in the server setup which overwrote the export of the CustomEnvironment with an express server.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tyler2P