【问题标题】:Mock ReadableStream模拟可读流
【发布时间】:2020-05-17 12:42:05
【问题描述】:

考虑以下代码:

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 部分数据(请参阅 pieces 数组):

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 那样完全模拟它吗?

【问题讨论】:

    标签: javascript unit-testing fetch sinon readable


    【解决方案1】:

    手动模拟它:

    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 }
              );
            },
          };
        },
      },
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-24
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 2010-12-19
      • 1970-01-01
      相关资源
      最近更新 更多