使用Jest和Sinon使用属性测试功能

时间:2020-02-18 13:50:29

标签: node.js jestjs sinon

我试图编写测试以测试我的应用程序上的流,并使用其fs函数处理createWriteStream库,因此我创建的存根如下:

writeStreamStub = sinon.stub()
onceStreamEventStub = sinon.stub()
endStreamStub = sinon.stub()
onStreamStub = sinon.stub()

createStreamStub = sinon.stub(fs, 'createWriteStream').returns({
  write: writeStreamStub,
  once: onceStreamEventStub,
  end: endStreamStub,
  on: onStreamStub
})

所以现在我可以测试是否调用了这些函数以及是否还调用了返回的函数。但是我正在使用--coverage标志,返回的函数的回调代码未涵盖,write方法在process.nextTick内部被调用,我不知道该怎么做这个。是否可以覆盖整个代码以及回调中的代码,如果可以,我该如何处理。预先感谢。

N.B。变量是全局声明的

1 个答案:

答案 0 :(得分:1)

如果没有充分的理由同时使用sinon和jest,我建议只使用一个库。如果您决定开玩笑,这是一个简单的示例。假设您有类似的课程

const fs = require('fs');

module.exports = class FileWriter {
  constructor() {
    this.writer = fs.createWriteStream('./testfile.txt');
  }

  writeFile() {
    process.nextTick(() => {
      this.writeContent('hello world');
    });
  }

  writeContent(content) {
    this.writer.write(content);
    this.writer.end();
  }

};

,在单元测试中,您想模拟所有使用的fs函数(在这种情况下,createWriteStream,writer,end)的行为,并检查是否使用正确的参数调用了它们。您可以通过以下方式进行此操作:

const fs = require('fs');
const FileWriter = require('./FileWriter');
// use this to have mocks for all of fs' functions (you could use jest.fn() instead as well)
jest.mock('fs');
describe('FileWriter', () => {
  it('should write file with correct args', async () => {
    const writeStub = jest.fn().mockReturnValue(true);
    const endStub = jest.fn().mockReturnValue(true);
    const writeStreamStub = fs.createWriteStream.mockReturnValue({
      write: writeStub,
      end: endStub,
    });

    const fileWriter = new FileWriter();
    fileWriter.writeFile();
    await waitForNextTick();
    expect(writeStreamStub).toBeCalledWith('./testfile.txt');
    expect(writeStub).toBeCalledWith('hello world');
    expect(endStub).toHaveBeenCalled();
  });
});

function waitForNextTick() {
  return new Promise(resolve => process.nextTick(resolve));
}