How do I stub node.js built-in fs during testing?

前端 未结 11 2111
暖寄归人
暖寄归人 2021-02-05 02:21

I want to stub node.js built-ins like fs so that I don\'t actually make any system level file calls. The only thing I can think to do is to pass in fs

11条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 02:52

    I like using rewire for stubbing out require(...) statements

    Module Under test

    module-a.js

    var fs = require('fs')
    function findFile(path, callback) {
      fs.readdir(path, function(err, files) {
         //Do something.
      })
    }
    

    Test Code

    module-a-test.js

    var rewire = require('rewire')
    var moduleA = rewire('./moduleA')
    // stub out fs
    var fsStub = {
      readdir: function(path, callback) {
         console.log('fs.readdir stub called')
         callback(null, [])
      }
    }
    moduleA.__set__('fs', fsStub)
    // call moduleA which now has a fs stubbed out
    moduleA()
    

提交回复
热议问题