Javascript Jest automock失败:类型错误:fs.readdirSync不是函数
我正在尝试生成“fs”模块的自动模拟,然后对其进行扩展,但我的实现不起作用:Javascript Jest automock失败:类型错误:fs.readdirSync不是函数,javascript,node.js,jestjs,Javascript,Node.js,Jestjs,我正在尝试生成“fs”模块的自动模拟,然后对其进行扩展,但我的实现不起作用: // /home/user/cp/projectName/__mocks__/fs.js const fs = jest.createMockFromModule('fs'); function readdirSync(fileName) { console.log(`The file name passed to this fake fs.readdirSync method is: ${fileName}`
// /home/user/cp/projectName/__mocks__/fs.js
const fs = jest.createMockFromModule('fs');
function readdirSync(fileName) {
console.log(`The file name passed to this fake fs.readdirSync method is: ${fileName}`);
return 'return value from fake fs.readdirSync';
}
function specialMethod() {
return 'returned from the special method';
}
fs.readdirSync = readdirSync;
fs.specialMethod = specialMethod;
exports = fs;
上述\uuuu mocks\uuuu
文件夹是节点模块
文件夹的同级
运行测试文件似乎忽略了上述模拟模块:
// /home/user/cp/projectName/src/captureCallData/__tests__/unit.test.ts
/* eslint-disable no-undef */
jest.mock('fs');
const fs = require('fs');
test('test fs.specialMethod', () => {
const result = fs.specialMethod();
});
function useFsInternally(fakeFileName: string) {
return fs.readdirSync(fakeFileName);
}
test('test mocking functionality', () => {
const result: string = useFsInternally('testInput');
expect(result).toStrictEqual('wrong value');
});
也尝试过
和import
语法,而不是export
。在这种情况下,实际的fs模块似乎要导入,而不是模拟模块:require()
exports
是初始等于模块的局部变量。exports
包含对导出对象的引用。它应该是变异的,而不是重新分配的exports=fs
仅替换局部变量的值,不影响导出的值
应该是
module.exports = fs;
或
"dependencies": {
"typescript": "^3.9.7"
},
"devDependencies": {
"@types/jest": "^26.0.9",
"jest": "^26.2.2",
"ts-jest": "^26.1.4"
}
src/captureCallData/__tests__/unit.test.ts:12:21 - error TS2339: Property 'specialMethod' does not exist on type 'typeof import("fs")'.
12 const result = fs.specialMethod();
~~~~~~~~~~~~~
src/captureCallData/__tests__/unit.test.ts:20:9 - error TS2322: Type 'string[]' is not assignable to type 'string'.
20 const result: string = useFsInternally('testInput');
~~~~~~
module.exports = fs;
Object.assign(exports, fs);