模拟ReadableStream

时间:2020-01-31 20:24:26

标签: javascript unit-testing fetch sinon readable

考虑以下代码:

fetch("/").then(response => {
  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  let res = 0;

  return reader.read().then(function processResult(result) {
    if (result.done) {
      return res;
    }

    const part = decoder.decode(result.value, { stream: true });

    res += part.length;

    return reader.read().then(processResult);
  });
}).then(res => console.log(res));

现在我要测试它。我嘲笑fetch返回应该提供一些读者的假response。我希望该读者返回数据的2部分(请参见data数组):

import { stub } from "sinon";

const pieces = [
  new Uint8Array([65, 98, 99, 32, 208]), // "Abc " and first byte of "й"
  new Uint8Array([185, 209, 139, 209, 141]), // Second byte of "й" and "ыэ"
];

const fetchStub = stub(window, "fetch");

fetchStub.returns(Promise.resolve({
  body: {
    getReader() {
      // What's here?
    },
  },
}));

有什么我可以简单地用getReader编写的,还是应该像使用fetch一样完全模拟?

1 个答案:

答案 0 :(得分:0)

手动模拟:

fetchStub = stub(window, "fetch");

fetchStub.returns(Promise.resolve({
  body: {
    getReader() {
      let i = 0;

      return {
        read() {
          return Promise.resolve(
            i < pieces.length
              ? { value: pieces[i++], done: false }
              : { value: undefined, done: true }
          );
        },
      };
    },
  },
}));