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

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

    Here's a version that works with the fs.promises api:

    const fsMock = sinon.mock(fs.promises);
    fsMock.expects('readFile').withArgs('test.json').returns(Promise.resolve(Buffer.from('{}')));
    
    const val = await fs.promises.readFile('test.json');
    
    expect(val.toString()).toEqual('{}');
    fsMock.verify();
    

提交回复
热议问题