NodeJS 在单元测试中使用迭代器不会解析值

kmbjn2e3  于 2023-11-17  发布在  Node.js
关注(0)|答案(2)|浏览(99)

bounty将在3天后过期。回答此问题可获得+100声望奖励。user686483正在寻找规范答案:您好,我希望收到允许每次迭代Assert和调用函数的答案。我还希望解释我在代码中做错了什么。

我有一个来自chatGPT的可读流,我试图使用一个juncIteratorAssert它,然后阅读这些值并Assert它们。jest测试运行良好,但我的逻辑中有一个错误,它在每次迭代后停止解析。
我错过了什么?
谢谢吉米

var util = require("util");

describe("stream", () => {
  it("should work", async () => {
    let i = -1;
    const completionStream: ChatCompletionStreamParams = {
      toReadableStream: () => {
        const mockReadable = {
          async *[Symbol.asyncIterator]() {
            const encoder = new util.TextEncoder("utf-8");
            yield encoder.encode(
              JSON.stringify({
                id: "1",
                object: "text",
                created: 1629159835,
                model: "gpt4",
                choices: [
                  {
                    index: 0,
                    delta: { content: "Hello" },
                    finish_reason: null,
                  },
                ],
              })
            ).buffer;
            yield encoder.encode(
              JSON.stringify({
                id: "1",
                object: "text",
                created: 1629159835,
                model: "gpt4",
                choices: [
                  {
                    index: 0,
                    delta: { content: "there" },
                    finish_reason: null,
                  },
                ],
              })
            ).buffer;
            yield null;
          },
          getReader: () => {
            return {
              read: async () => {
                const result = await mockReadable[
                  Symbol.asyncIterator
                ]().next();
                i++;
                if (i >= 2) {
                  return Promise.resolve({ done: true, value: null });
                }
                return Promise.resolve({ done: false, value: result?.value });
              },
            };
          },
        };
        return mockReadable;
      },
    };

    const readable = completionStream.toReadableStream().getReader();

    while (true) {
      const { done, value } = await readable.read();
      expect(done).toBe(false); // assert here
    }
  });
});

字符串

yqkkidmi

yqkkidmi1#

你在getReader中的mockReadable[Symbol.asyncIterator]()部分犯了一个错误。它在你每次调用readable.read()时都会被调用,这会从头开始创建一个freshxrc迭代器,因此它一直返回“Hello”,永远不会到达“there”。
您需要保存迭代器并重用它。

getReader: () => {
  const iterator = mockReadable[Symbol.asyncIterator]();
  return {
    read: async () => {
      const result = await iterator.next();
      return result;
    }

    // in fact you can just re-expose `iterator.next` as `read` like
    // read: iterator.next.bind(iterator),
  };
}

字符串

iugsix8n

iugsix8n2#

它将工作文件:

it("should work", async () => {
  let i = -1;
  const completionStream: ChatCompletionStreamParams = {
    toReadableStream: () => {
      const mockReadable = {
        async *[Symbol.asyncIterator]() {
          const encoder = new util.TextEncoder("utf-8");
          yield encoder.encode(
            JSON.stringify({
              id: "1",
              object: "text",
              created: 1629159835,
              model: "gpt4",
              choices: [
                {
                  index: 0,
                  delta: { content: "Hello" },
                  finish_reason: null,
                },
              ],
            })
          ).buffer;
          yield encoder.encode(
            JSON.stringify({
              id: "1",
              object: "text",
              created: 1629159835,
              model: "gpt4",
              choices: [
                {
                  index: 0,
                  delta: { content: "there" },
                  finish_reason: null,
                },
              ],
            })
          ).buffer;
          yield null;
        },
        getReader: () => {
          return {
            read: async () => {
              const result = await mockReadable[
                Symbol.asyncIterator
              ]().next();
              i++;
              if (i >= 2) {
                return Promise.resolve({ done: true, value: null });
              }
              return Promise.resolve({ done: false, value: result?.value });
            },
          };
        },
      };
      return mockReadable;
    },
  };

  const readable = completionStream.toReadableStream().getReader();

  while (true) {
    const { done, value } = await readable.read();
    expect(done).toBe(false); // assert here

    if (done) {
      break; // exit the loop when done is true
    }
  }
});

字符串

相关问题