NestJS 抛出错误找不到模块 'jest-util'

NestJS throwing error Cannot find module 'jest-util'

我是 运行 一个 NestJS api,拥有丰富的代码,一切正常,并且它几乎覆盖了各种不同模拟的完整代码。

在尝试为新模块的提供者实施测试时,系统提示我出现此错误:

Cannot find module 'jest-util'
Require stack:
- /node_modules/jest-runtime/build/index.js
- /node_modules/@jest/core/build/cli/index.js
- /node_modules/@jest/core/build/jest.js
- /node_modules/jest-cli/build/cli/index.js
- /node_modules/jest-cli/bin/jest.js
- /node_modules/jest/bin/jest.js

  at Function.Module._resolveFilename (../node:internal/modules/cjs/loader:933:15)
  at Function.Module._load (../node:internal/modules/cjs/loader:778:27)
  at Module.require (../node:internal/modules/cjs/loader:999:19)
  at require (../node:internal/modules/cjs/helpers:102:18)

我设法找出导致此行为的原因,就是下面的这段代码:

jest.mock("fs", () => ({
   promises: {
       writeFile: jest.fn().mockResolvedValue(undefined),
       readFile: jest.fn().mockResolvedValue(Buffer.from('test')),
       unlink: jest.fn().mockResolvedValue(undefined),
   },
}));

此语句下方和上方的其余代码中都使用了 Jest 函数,因此对我来说发生的事情有点不合理。

我想有些人会想看 package.json 上的笑话部分,所以我在下面添加了它,但我认为这不是问题所在,因为它在超过 1000不同的测试,都与这个非常相似。

"jest": {
"moduleFileExtensions": [
  "js",
  "json",
  "ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
  "^.+\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
  "**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"coverageReporters": [
  "json-summary",
  "json",
  "html"
],
"testEnvironment": "node",
"setupFiles": [
  "<rootDir>/test/config/envMock.ts"
]
},

jest 版本是 25.1.0

有人知道发生了什么事吗?

我在测试模块的 beforeEach 块上已经存在的 clearAllMocks 之后添加了一个 restoreAllMocks,错误消失了。

虽然不知道确切原因。我想这可能与代码中某些点的模拟状态有关,但我真的不知道。