Рассмотрим следующий код:
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