开玩笑,抛出有关 node_modules 依赖项内导入的引用错误

Mic*_*elB 9 jestjs nestjs nestjs-testing

我有一个 Nestjs monorepo 应用程序,可以通过 Jest 进行工作测试。这与全局单元测试有关,该测试从 package.json 中的 Nestjs CLI 创建的配置中获取配置。

我的 storage.service.ts 使用jimp其方法之一来调整图像大小。

这具有@jimp/types依赖关系 取决于@jimp/gif取决于gifwrap

对于在我的控制台中运行的每个测试,我都会看到以下错误:

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

      at node_modules/.pnpm/gifwrap@0.9.2/node_modules/gifwrap/src/gifcodec.js:7:15
Run Code Online (Sandbox Code Playgroud)

我还使用 beforeAll() 和 afterAll() 钩子来关闭 Nestjs 模块。

笑话配置:

  "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": {
...
Run Code Online (Sandbox Code Playgroud)

我怎样才能消除这个错误,或者甚至大胆地修复它?

小智 5

我遇到了同样的问题,并且仅当测试同步时才会出现该问题。
最小超时可以解决问题:

afterAll(async () => {
  await new Promise(resolve => setTimeout(resolve));
});
Run Code Online (Sandbox Code Playgroud)

或者

afterAll(done => {
  setTimeout(done);
});
Run Code Online (Sandbox Code Playgroud)