Serg
Serg

Reputation: 7475

Mocking specific reading file error for tests in Node.js

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.

Upvotes: 2

Views: 1068

Answers (1)

lependu
lependu

Reputation: 1153

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

Upvotes: 1

Related Questions