Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest throwing reference error about an import inside a node_modules dependency

I have a nestjs monorepo application with working tests via Jest. This is in relation to the global unit tests which take their configuration from the nestjs CLI-created configuration within package.json.

My storage.service.ts uses jimp in one of its methods to resize an image.

This has @jimp/types dependency that depends on @jimp/gif which depends on gifwrap.

For every test that runs in my console, I see this error:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at node_modules/.pnpm/[email protected]/node_modules/gifwrap/src/gifcodec.js:7:15

I'm also using beforeAll() and afterAll() hook to close the nestjs module.

Jest config:

  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": ".",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "./coverage",
    "testEnvironment": "node",
    "roots": [
      "<rootDir>/apps/",
      "<rootDir>/libs/"
    ],
    "moduleNameMapper": {
...

How can I silence this error or perhaps even be as bold as fixing it?

like image 967
SebastianG Avatar asked Nov 07 '22 02:11

SebastianG


1 Answers

I had the same problem, and the issue occurs only if the test is synchronous.
A minimal timeout solves the problem:

afterAll(async () => {
  await new Promise(resolve => setTimeout(resolve));
});

or

afterAll(done => {
  setTimeout(done);
});
like image 113
sky Avatar answered Dec 01 '22 12:12

sky