What Works vs. What Doesn’t
The Unit Test
// my-func.test.js
import { jest } from '@jest/globals';
import { myFunc } from './my-func.js';
import fs from 'node:fs';
const mock = jest.fn().mockReturnValue({isDirectory: () => true});
jest.spyOn(fs, 'statSync').mockImplementation(mock);
it('should work', () => {
expect(myFunc('/test')).toBeTruthy();
expect(mock).toHaveBeenCalled();
});
The Working Version
// my-func.js
import fs from 'node:fs';
// import { statSync } from 'node:fs';
export function myFunc(dir) {
const stats = fs.statSync(dir, { throwIfNoEntry: false });
// const stats = statSync(dir, { throwIfNoEntry: false });
return stats.isDirectory();
}
The Failing Version
Note the different importing mechanism. Jest will fail with:
Cannot read properties of undefined (reading ‘isDirectory’)
TypeError: Cannot read properties of undefined (reading ‘isDirectory’)
// my-func.js
// import fs from 'node:fs';
import { statSync } from 'node:fs';
export function myFunc(dir) {
// const stats = fs.statSync(dir, { throwIfNoEntry: false });
const stats = statSync(dir, { throwIfNoEntry: false });
return stats.isDirectory();
}
The Question
How do I spy on or mock statSync
using the import { statSync } from 'node:fs';
syntax, or is it even possible?
Environment
Note that the test is being run in the ESModule mode.
# package.json
{
"type": "module",
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
...
},
"devDependencies": {
"@eslint/js": "^9.17.0",
"@jest/globals": "^29.7.0",
"globals": "^15.14.0",
"jest": "^29.7.0",
...
},
...
}