如何用jest模拟和测试fs. ssl ReadStream?

cunj1qz1  于 11个月前  发布在  Jest
关注(0)|答案(1)|浏览(122)

我有一个函数,我在其中使用了fs. fs ReadStream,我想模拟它,这样我就可以测试,例如,函数Test在接收数据时被调用,函数Test 2在流结束时被调用。
代码是这样的:

const readStream = fs.createReadStream(filePath, { highWaterMark: 260 * 1000 });

  readStream.on("data", (chunk) => {
    functionTest();
  });
  readStream.on("end", (chunk) => {
    functionTest2("example")
  });

字符串
我看了一下mock-fs和memfs,但老实说我很困惑,不知道哪条路是正确的

emeijp43

emeijp431#

为了使函数可测试,我将其分为两部分:
1.返回流的函数-我可以通过检查返回值示例来测试这一点
1.一个处理流的函数-我可以通过传递可读的流来测试它

function getFileStream() {
  return fs.createReadStream(filePath, { highWaterMark: 260 * 1000 });
}

function handleStream(readStream, dataCallback, endCallback) {
  readStream.on("data", (chunk) => {
    dataCallback();
  });
  readStream.on("end", (chunk) => {
    endCallback("example")
  });
}

function handleFile(filePath, dataCallback, endCallback) {
  const stream = getFileStream(filePath);
  handleStream(stream, dataCallback, endCallback);
}

...
...
// In test file

const dataCallback = jest.fn(...);
const endCallback = jest.fn(...);
test('Expect callbacks to be called once', () => {
  const readable = stream.Readable({
    read() {}
  });
  
  handleStream(readable, dataCallback, endCallback);

  readable.push('Hello'); // Emits data event
  readable.push(null); // Emits end event

  expect(dataCallback.mock.calls).toHaveLength(1);
  expect(endCallback.mock.calls).toHaveLength(1);

});

字符串

相关问题