【问题标题】:mock fs.readFile - Unit test模拟 fs.readFile - 单元测试
【发布时间】:2020-05-04 23:45:37
【问题描述】:

我正在使用 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**/   
    });
};

简而言之,我要做什么

如何正确模拟 fs.readFile ?

编辑
当我试图在我的原始回调函数中解决错误时,它抛出了错误“没有这样的文件”。但我希望错误为空,因为我正在模拟它以将值返回为空。

【问题讨论】:

  • 我刚刚用function myFunction(path) { fs.readFile(path, (error, res) => console.log('error', error, 'res', res)); } 进行了测试,它工作正常。你确定你的功能没有问题吗? 编辑:注意回调不应该是async
  • 我刚刚用你的版本进行了测试,它似乎工作正常。当前输出是多少?
  • 是的,我的回调是异步的,因为它在里面做了一些数据库工作。我现在应该做什么?
  • 使用您的代码时测试通过。您确定要在两个地方导入相同的 fs 模块吗?你能发布一个完整的例子(包括导入的所有文件)吗?
  • 是的,这就是问题所在!导入语句不同..谢谢

标签: javascript typescript unit-testing jestjs fs


【解决方案1】:

感谢@JC Olivares,

'fs'导入是这里的问题。在测试用例文件中,我将'fs'导入为

import * as fs from 'fs';

但是带有函数的文件有导入

import fs from 'fs';

【讨论】:

    猜你喜欢
    • 2013-02-22
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 2021-12-08
    相关资源
    最近更新 更多