如何模拟fs.readFile返回的错误以进行测试?

Ant*_*ony 4 unit-testing mocha.js fs node.js chai

我是测试驱动开发的新手,我正在尝试为我的应用程序开发一个自动化测试套件.

我已成功编写测试来验证从成功调用Node的fs.readFile方法收到的数据,但正如您将在下面的屏幕截图中看到的,当我使用istanbul模块测试我的覆盖时,它正确显示我没有测试过这个案例从fs.readFile返回错误的位置.

在此输入图像描述

我怎样才能做到这一点?我有一种预感,我必须模拟一个文件系统,我尝试使用mock-fs模块,但没有成功.该函数的路径是硬编码的,我使用重新连接从我的应用程序代码调用未导出的函数.因此,当我使用rewire的getter方法访问getAppStatus函数时,它使用真正的fs模块,因为这是getAppStatus所在的async.js文件中使用的模块.

这是我正在测试的代码:

// check whether the application is turned on
function getAppStatus(cb){
  fs.readFile(directory + '../config/status.js','utf8', function(err, data){
    if(err){
      cb(err);
    }
    else{
      status = data;
      cb(null, status);
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

这是我为返回数据的情况编写的测试:

  it('application should either be on or off', function(done) {
      getAppStatus(function(err, data){
        data.should.eq('on' || 'off')

        done();
      })
  });
Run Code Online (Sandbox Code Playgroud)

我使用Chai作为断言库并使用Mocha运行测试.

允许我模拟从fs.readFile返回的错误的任何帮助,所以我可以为这个场景编写测试用例非常感谢.

Pie*_*ert 6

更好的是使用mock-fs,如果你没有提供文件,它将返回ENOENT.在测试后请小心调用恢复,以避免对其他测试产生任何影响.

在开头添加

  var mock = require('mock-fs');
Run Code Online (Sandbox Code Playgroud)

而且测试

before(function() {
  mock();
});
it('should throw an error', function(done) {
  getAppStatus(function(err, data){
    err.should.be.an.instanceof(Error);
    done();
  });
});
after(function() {
  mock.restore();
});
Run Code Online (Sandbox Code Playgroud)