I'm trying to add jest to my typescript project for testing, but when I run jest, it keeps giving me the error
● Test suite failed to run
Cannot find module 'fs/promises' from 'src/path/to/file'
Require stack:
src/path/to/file
test/test.ts
> 3 | import fsp from 'fs/promises';
at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:311:11)
at Object.<anonymous> (src/path/to/file.ts:3:1)
The program itself runs fine, but whenever I try to run jest on it, it runs into this issue. I've tried adding jest.mock('fs');, which didn't help, and adding jest.mock('fs/promises'); gives the same error in the test file.
I've read that certain versions of Node don't support 'fs/promises' and instead need require('fs').promises, which I've tried and still doesn't work (I'm on Node version 12).
How can I configure jest to be able to load 'fs/promises'? I've included my jest.config.js file below:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: [
'/node_modules/',
'/out/',
],
moduleDirectories: [
'.',
'node_modules'
],
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx'
]
}
Turns out Jest is interpreting 'fs/promises' as a folder in the file system, which is incorrect as this is an API from the fs module. To fix this, simply add
moduleNameMapper: {
"fs/promises": "<rootDir>/node_modules/fs-extra/lib/fs"
}
to jest.config.js to tell Jest to map the module 'fs/promises' to the file <rootDir>/node_modules/fs-extra/lib/fs, or wherever the fs module is defined in your file system.