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.

Serg
  • 6,742
  • 4
  • 36
  • 54

1 Answers1

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

lependu
  • 1,160
  • 8
  • 18
  • `ReadingFileError` is a custom class that inherits from `Error`. – Serg Nov 16 '18 at 11:30
  • 1
    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 :) – lependu Nov 16 '18 at 11:31