14

I am trying to create a custom test environment with Jest as described in their official docs
Unfortunately I get the following error:

Determining test suites to run...
FAIL acceptancetests/mongo.test.js
● Test suite failed to run

TypeError: TestEnvironment is not a constructor

at ../node_modules/jest-runner/build/run_test.js:88:25

My test is completely empty and my CustomTestEnvironment just calls the super classes. I am on the latest Jest version (24.3.1)

I think it is very weird, that the error is thrown within the Jest library.

This is my test-environment.js:

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

class CustomEnvironment extends NodeEnvironment {
  constructor(config) {
    super(config);
  }

  async setup() {
    await super.setup();
  }

  async teardown() {
    await super.teardown();
  }

  runScript(script) {
    return super.runScript(script);
  }
}

Any help is appreciated!

Community
  • 1
  • 1
JDurstberger
  • 4,127
  • 8
  • 31
  • 68

1 Answers1

12

Ok, this is a silly problem and I found the solution.

I had to export the CustomEnvironment

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

class CustomEnvironment extends NodeEnvironment {
  ...
}

module.exports = CustomEnvironment

And also add it in the jest.config.js

const { defaults } = require("jest-config");
module.exports = {
  testEnvironment: './../CustomEnvironment.js',
};

I don't know why the guide doesn't include that line :(

JRichardsz
  • 14,356
  • 6
  • 59
  • 94
JDurstberger
  • 4,127
  • 8
  • 31
  • 68
  • I have the same problem, but I do export. What does your config file look like? – Remko Aug 30 '18 at 08:41
  • 5
    Found it: you have to set the path to the file exporting the class in jest.config.js at ``testEnvironment`` – Remko Aug 30 '18 at 09:05
  • 1
    I also had an issue with the file naming conventions. If you don't include a relative directory in part of the path such as `--test-environment env.js` it will assume you're trying to import something from `node_modules`. The proper way to import a file would be to say `--test-environment ./env.js` – Evan Siroky Jan 16 '19 at 23:58
  • 2
    I found that in my `jest.config.js` I had to do this: `testEnvironment: '/../jest/environment.js',` Where my `rootDir` was `src` off of the project root. – tvsbrent Jul 27 '20 at 18:09
  • 1
    `Class extends value # is not a constructor or null`. What I've done wrong? – testing_22 Jan 12 '23 at 01:27
  • @testing_22 answered here: https://stackoverflow.com/a/76124222/7761396 – taubhi Apr 27 '23 at 20:03