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

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

    Stubs are functions/programs that simulate the behaviors of components/modules. Stubs provide canned answers to function calls made during test cases.

    An example can be writing a file, without actually doing so.

    var fs = require('fs')
    
    var writeFileStub = sinon.stub(fs, 'writeFile', function (path, data, cb) {  
     return cb(null)
    })
    
    expect(writeFileStub).to.be.called  
    writeFileStub.restore()  
    

提交回复
热议问题