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

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

    Rewire and other stubbing solutions are good if the module under test is the one making calls to fs itself. However, if the module under test uses a library which uses fs underneath, rewire and other stubbing solution get hairy pretty quickly.

    There is a better solution now: mock-fs

    The mock-fs module allows Node's built-in fs module to be backed temporarily by an in-memory, mock file system. This lets you run tests against a set of mock files and directories instead of lugging around a bunch of test fixtures.

    Example (shamelessly lifted from its readme):

    var mock = require('mock-fs');
    
    mock({
      'path/to/fake/dir': {
        'some-file.txt': 'file content here',
        'empty-dir': {/** empty directory */}
      },
      'path/to/some.png': new Buffer([8, 6, 7, 5, 3, 0, 9]),
      'some/other/path': {/** another empty directory */}
    });
    

提交回复
热议问题