我正在使用Jest框架进行单元测试,并且遇到了模拟fs.readFile的场景。我使用了spyOn并模拟了实现。下面的代码是我的代码
test_file.ts
import * as fs from 'fs';
it('read File', () => {
const spy = jest.spyOn(fs, 'readFile')
.mockImplementation((_, callback) => callback(null, Buffer.from('Sample')));
// Calling the function
myFunction('./path');
expect(spy).toHaveBeenCalled();
});
当我运行测试用例并且模拟不起作用时,间谍没有被调用。原始实现始终可以起作用。
我的使用fs.readFile的函数
myFunction = (path) => {
// Reading the file
fs.readFile(path, async (error, file) => {
console.log(error) // No such file error thrown instead of null
/** Block of code with async work**/
});
};
简而言之,我想做什么
编辑当我尝试控制原始回调函数中的错误时,抛出了错误“ no such file”。但是我期望该错误为null,因为我正在模拟它以将值返回为null。
感谢@JC Olivares,
'fs'导入是这里的问题。在测试用例文件中,我将'fs'导入为
import * as fs from 'fs';
但是具有功能的文件已导入
import fs from 'fs';