I'm running a NestJS api with extensive code, everything is working fine, and it has almost full code coverage with all kinds of different mocks.
While trying to implement a test for the provider of a new module, I was prompted with this error:
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)
I managed to isolate what was causing this behavior and it was this snippet of code below:
jest.mock("fs", () => ({
promises: {
writeFile: jest.fn().mockResolvedValue(undefined),
readFile: jest.fn().mockResolvedValue(Buffer.from('test')),
unlink: jest.fn().mockResolvedValue(undefined),
},
}));
Jest functions are being used all over the rest of the code below and above this statement, so it kinda doesn't make sense for me what is going on.
I expect some people are gonna wanna see the jest section on the package.json so I've added it below, but I don't think that's where the problem lies, as its working in more than 1000 different tests, all very similar to this one.
"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 version is 25.1.0
Anyone has any idea what is going on?
CodePudding user response:
I added a restoreAllMocks
after the already existing clearAllMocks
on the beforeEach
block of the testing module and the error went away.
Don't know exactly why though. I guess that maybe it has something to do with the mocks' states at certain points in the code, but I have no idea really.