Mocking specific reading file error for tests in Node.js












1















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.










share|improve this question



























    1















    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.










    share|improve this question

























      1












      1








      1








      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.










      share|improve this question














      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.







      node.js unit-testing mocking fs






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 16 '18 at 8:07









      SergeySergey

      1,3361425




      1,3361425
























          1 Answer
          1






          active

          oldest

          votes


















          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:





          • proxyquire (see example below)

          • testdouble



          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






          share|improve this answer


























          • ReadingFileError is a custom class that inherits from Error.

            – Sergey
            Nov 16 '18 at 11:30











          • 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














          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53333758%2fmocking-specific-reading-file-error-for-tests-in-node-js%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          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:





          • proxyquire (see example below)

          • testdouble



          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






          share|improve this answer


























          • ReadingFileError is a custom class that inherits from Error.

            – Sergey
            Nov 16 '18 at 11:30











          • 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


















          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:





          • proxyquire (see example below)

          • testdouble



          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






          share|improve this answer


























          • ReadingFileError is a custom class that inherits from Error.

            – Sergey
            Nov 16 '18 at 11:30











          • 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
















          1












          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:





          • proxyquire (see example below)

          • testdouble



          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






          share|improve this answer















          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:





          • proxyquire (see example below)

          • testdouble



          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







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 16 '18 at 19:04

























          answered Nov 16 '18 at 11:19









          lependulependu

          724314




          724314













          • ReadingFileError is a custom class that inherits from Error.

            – Sergey
            Nov 16 '18 at 11:30











          • 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





















          • ReadingFileError is a custom class that inherits from Error.

            – Sergey
            Nov 16 '18 at 11:30











          • 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



















          ReadingFileError is a custom class that inherits from Error.

          – Sergey
          Nov 16 '18 at 11:30





          ReadingFileError is a custom class that inherits from Error.

          – Sergey
          Nov 16 '18 at 11:30













          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







          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






















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53333758%2fmocking-specific-reading-file-error-for-tests-in-node-js%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          The Sandy Post

          Danny Elfman

          Pages that link to "Head v. Amoskeag Manufacturing Co."