簡體   English   中英

模擬可讀流

[英]Mock ReadableStream

考慮以下代碼:

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編寫的getReader或者我應該像使用fetch一樣完全模擬它?

手動模擬它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM