"Right-hand side of 'instanceof' is not an object" when testing NestJS + TypeORM using Jest

Viewed 1998

I have a working NestJS server that performs some TypeORM repository.insert() command. However when running the same operation from a Jest test (using @nestjs/testing's Test.createTestingModule(...), the infamous Right-hand side of 'instanceof' is not an object appears.

Looking in more details, it appears that this is due to some dynamic loading occurring in TypeORM's QueryBuilder:

// loading it dynamically because of circular issue
const InsertQueryBuilderCls = require("./InsertQueryBuilder").InsertQueryBuilder;

That line succeeds when running the NestJS server but fails when running the Jest test. More specifically:

  • in the NestJS server: QueryBuilder require("./InsertQueryBuilder") returns an ES module with a InsertQueryBuilder in it. When setting a breakpoint here, strangely the debugged file appears located at src/query-builder/QueryBuilder.ts (which is non-existent, and should rather be node_modules/typeorm/query-builder/QueryBuilder.js), but this succeeds.
  • in the Jest test: require("./InsertQueryBuilder") return an empty object, and so InsertQueryBuilder is undefined which not an object indeed. The debugged file is as expected node_modules/typeorm/query-builder/QueryBuilder.js, but this fails.

I looks like it could be related to my Jest configuration, which is:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  moduleDirectories: ['node_modules', 'src']
}

as my Typescript sources are under a src directory under the project root. Those path issues are also be related to my tsconfig.json, which contains:

{
  "compilerOptions": {
  "module": "commonjs",
  "allowSyntheticDefaultImports": true,
  "target": "es2019",
  "baseUrl": "./src",
  "outDir": "./dist",
  "incremental": true,
  "lib": [
    "es2019"
  ]
}
0 Answers
Related