7

我有一个通过 Jest 进行工作测试的 nestjs monorepo 应用程序。这与全局单元测试有关,它们从 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

我还使用 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": {
...

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

4

3 回答 3

3

我遇到了同样的问题,只有在测试同步时才会出现问题。
最小超时解决了这个问题:

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

或者

afterAll(done => {
  setTimeout(done);
});
于 2021-08-20T15:53:21.150 回答
1

配置timersin jest configmodern为我解决了这个问题:jest-docs

"timers": "modern",
于 2021-11-08T13:08:40.540 回答
0

不确定它是否会对您的情况有所帮助,但我在我的打字稿项目中解决它的方法是模拟 jimp 导入本身。我正在测试一个使用一些包含 Jimp 的类的类。与其嘲笑所有这些,嘲笑 jimp 更容易。

jest.mock('jimp', () => {
  return {};
}

我把它放在我的导入下面和我的测试之前。根据您正在做的事情,您可能还需要更深入地了解您的模拟。例子:

jest.mock('jimp', () => {
  return {
    read: jest.fn().mockImplementation(),
  };
});

我在 jest 25 上做到了,但我认为它也适用于大多数其他版本。

我的 jest.config.js 文件:

module.exports = {
  moduleFileExtensions: ['js', 'json', 'ts'],
  rootDir: 'src',
  testRegex: '\\.spec\\.ts$',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/$1',
    '^src/(.*)$': '<rootDir>/$1',
  },
  testPathIgnorePatterns: ['e2e/'],
  coverageDirectory: '../coverage',
  testEnvironment: 'node',
};

process.env = Object.assign(process.env, {
  APP_ENV: 'development',
});
于 2021-10-19T01:51:45.783 回答