How to simulate the error returned from fs.readFile for testing purposes?

I am new to test driven development and am trying to develop an automated test suite for my application.

I have successfully written tests that validate the data received from a successful call against the Node fs.readFile method, but as you will see in the screenshot below, when I test my coverage with the istanbul module, it correctly displays that I have not tested the case. when error is returned from fs.readFile.

enter image description here

How can i do this? I have a hunch that I should mock the filesystem, which I tried using the mock-fs module but failed. The file path is hardcoded into the function and I am using rewire to call the non-exported function from my application code. So when I use the rewire getter method to access the getAppStatus function, it is using the real fs module, since that is what is used in the async.js file where getAppStatus resides.

Here's the code I'm testing:

// 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);
    }
  });
}

      

Here's the test I wrote for the return data case:

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

        done();
      })
  });

      

I am using Chai as my assertion library and runs tests with Mocha.

Any help to allow me to simulate the error returned from fs.readFile so that I can write a test case for this scenario is well appreciated.

+3


source to share


1 answer


Better to use mock-fs

if you don't provide any file to it, it will return ENOENT. Just be careful to trigger post-test recovery so as not to affect other tests.

Add at the beginning

  var mock = require('mock-fs');

      



And the test

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

      

+4


source







All Articles