0

I have a very simple test:

    beforeAll(async () => {
      try {
        await db.connect();
      } catch(e: any) {
        expect(e).toBeInstanceOf(Error);
      }
    });

but it fail with this really strange message

    expect(received).toBeInstanceOf(expected)

    Expected constructor: Error
    Received constructor: Error

so I suspect the value of Error while running a jest test is redefined.

jest.config.js:

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset:                 "ts-jest",
  testEnvironment:        "node",
  testPathIgnorePatterns: ["/node_modules/"]
};

partial package.json:

{
  "devDependencies": {
    "@types/jest": "28.1.3",
    "@types/node": "18.0.0",
    "jest": "28.1.1",
    "ts-jest": "28.0.5",
    "ts-node": "10.8.1",
    "typescript": "4.7.4",
  },
  "scripts": {
    "coverage": "jest --coverage",
    "test": "jest",
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "alwaysStrict": true,
    "esModuleInterop": true,
    "moduleResolution": "Node",
    "noImplicitAny": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "strict": true,
    "strictBindCallApply": true,
    "strictFunctionTypes": true,
    "strictNullChecks": true,
    "strictPropertyInitialization": true,
    "target": "ESNext"
  },
  "exclude": ["*.d.ts"],
  "include": ["*.ts", "test/*.ts"]
}
Daniele Ricci
  • 15,422
  • 1
  • 27
  • 55
  • 1
    I'd guess this is related to https://github.com/facebook/jest/issues/2549, but you should probably `expect(db.connect()).rejects.toThrow(Error)` instead. – jonrsharpe Jun 28 '22 at 16:40
  • 1
    Does [this question](https://stackoverflow.com/questions/46042613/how-to-test-the-type-of-a-thrown-exception-in-jest) answer your question? – Etheryte Jun 28 '22 at 16:40
  • Thanks to your comment, @jonrsharpe , I understood the reason. Since I don't need isolated contex (and sincerely the only reason I can see why we could need jest isolated context is to be free to write bad tests) I found very useful [jest-environment-node-single-context](https://www.npmjs.com/package/jest-environment-node-single-context). Thank you – Daniele Ricci Jun 28 '22 at 20:46

0 Answers0