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

2.1k views Asked by At

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

I have successfully written tests that verify the data received from a successful call to Node's 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 where an error is returned from fs.readFile.

enter image description here

How can I do this? I have a hunch that I have to mock up a file-system, which I have tried using the mock-fs module, but haven't succeeded. The path to the file is hard-coded in the function, and I am using rewire to call the unexported function from my application code. Therefore, when I use rewire's getter method to access the getAppStatus function, it uses the real fs module as that is what is used in the async.js file where getAppStatus resides.

Here's the code that I am 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 have written for the case where data is returned:

  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 an assertion library and running the tests with Mocha.

Any help in allowing me to simulate an error being returned from fs.readFile so I can write a test case for this scenario is well appreciated.

1

There are 1 answers

1
Pierre Inglebert On BEST ANSWER

The better is to use mock-fs, if you provide it no file, it will return ENOENT. Just be careful to call restore after your test to avoid any impact on 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();
});