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

前端 未结 11 2125
暖寄归人
暖寄归人 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:34

    An alternative (although I think Noah's suggestion of rewire is better):

    Write a wrapper around require, named requireStubbable or so. Put this in a module which you configure once, in test setup code. Because node caches result of require, whenever you require the requireStubbable module again, you'd get the same configured function. You could configure it so that any number of modules would be stubbed, all others would be passed on unchanged.

    Any module which you'd want to support passing in stubs need to use the requireStubbable function instead of regular require though. The rewire module does not have that drawback, and instead gives control to the calling code.

    Added April 26

    I've never realized, but since the object (or more precisely: object reference) returned by require("fs") is cached, you could simply do:

    const fs = require("fs")
    fs.readFile = function (filename, cb) {
      cb(null, new Buffer("fake contents"));
    };
    // etc
    

    When you include this code anywhere, fs.readFile will be pointing to the above function everywhere. This works for stubbing out any module that is a mere collection of functions (like most built-in modules). The cases for which it doesn't work if the module returns a sole function. For this, something like rewire would be necessary.

提交回复
热议问题