2

Is it possible to mock, let's say, with the "mock-fs" library some sort of reading file errors? In particular, I want to test this case (where code !== 'ENOENT'):

fs.readFile(filePath, (err, data) => {
    if (err) {
        if (err.code !== 'ENOENT') { 
            return done(new ReadingFileError(filePath));
        }
    }
    // ... 
});

I could find nothing about emulating reading errors in their docs. Maybe there are some other libraries that can do this.

1 Answer 1

1

As far as I know mock-fs mocks the filesystem not the node utility. Of course in some case you can use that to test the fs utility, but I think your use case is not amongs them.

Here is an example with sinon.sandbox

Some alternatives are:

Note, that I am a bit confused where the ReadingFileError comes from, so I guess you are trying to implement a custom error. If that is the case maybe this also will be helpful. In the example I replaced that with a simple new Error('My !ENOENT error').

// readfile.js
'use strict'

const fs = require('fs')

function myReadUtil (filePath, done) {
  fs.readFile(filePath, (err, data) => {
    if (err) {
      if (err.code !== 'ENOENT') {
        return done(err, null)
      }
      return done(new Error('My ENOENT error'), null)
    }
    return done(null, data)
  })
}

module.exports = myReadUtil

// test.js
'use strict'

const assert = require('assert')
const proxyquire = require('proxyquire')

const fsMock = {
  readFile: function (path, cb) {
    cb(new Error('My !ENOENT error'), null)
  }     
}


const myReadUtil = proxyquire('./readfile', { 'fs': fsMock })

myReadUtil('/file-throws', (err, file) => {
  assert.equal(err.message, 'My !ENOENT error')
  assert.equal(file, null)
})

Edit: Refactored the example to use node style callback instead of throw and try/catch

Sign up to request clarification or add additional context in comments.

2 Comments

ReadingFileError is a custom class that inherits from Error.
That is what I assumed (see note), but I don't have it, so I can't use it in the example. It does not change anything :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.