mock fs.readFile - 单元测试

mock fs.readFile - Unit test

我正在使用 Jest 框架进行单元测试,遇到了一个场景来模拟 fs.readFile.I 使用了 spyOn 并模拟了下面的 implementation.My 代码

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();

});

当我 运行 测试用例并且模拟不是 working.The 时,间谍不会被调用 working.The 原始实现始终有效。

我的函数使用 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**/   
    });
};

简而言之,我正在尝试做什么

如何正确模拟 fs.readFile?

编辑
当我试图控制我原来的回调函数中的错误时,它抛出了错误 'no such file' 。但是我期望错误为空,因为我将其模拟为 return 值为空。

感谢@JC Olivares,

'fs' 导入是问题 here.In 测试用例文件,我将 'fs' 导入为

import * as fs from 'fs';

但是带函数的文件有import

import fs from 'fs';