【问题标题】:Testing Async Generator with Jest用 Jest 测试异步生成器
【发布时间】:2021-10-27 12:19:23
【问题描述】:

显然,我对这应该如何工作存在很大的误解,尤其是在测试中(使用 Jest)。当我尝试执行 await... of 循环时,我什么也得不到。我传入生成器的文件路径是正确的,并且我已经在之前的测试中测试过该文件存在。

    expect(
      statSync('path/to/file.csv').isFile()
    ).toBe(true);

这是我的异步生成器,它返回文件行的承诺。 (我在另一个问题Maximum call stack size exceeded TypeScript Recursive Function returning a Generator returning a Promise问过这个问题)

export async function *lineOfFileGenerator(fullFilePath: string) {
  const filestream = createReadStream(fullFilePath);
  const rl = createInterface({
    input: filestream,
    crlfDelay: Infinity
  });
  for await (const line of rl) {
    yield line;
  }
}

请问如何访问 Jest 中的 yeilded 值?为了测试,我传入了一个小文件。

const gen = lineOfFileGenerator('path/to/file.csv');

for (await let retVal of gen) {
      console.log(retVal.value);
    }

如果我尝试登录 val.value,Jest 会抱怨。当我将这种东西添加到测试中时,它似乎根本没有进入循环,即使我尝试像“hello”这样的字符串也不会记录。当我测试调用这个生成器的函数时,我注意到它只被调用一次。

我错过了什么?

【问题讨论】:

    标签: node.js typescript testing jestjs ts-jest


    【解决方案1】:

    根据文档Iterating over async generators,迭代变量(retVal) 是异步生成器函数的值yield。它不是生成器,所以没有value 字段。

    例如

    const { createReadStream } = require('fs');
    const path = require('path');
    const readline = require('readline');
    
    async function* lineOfFileGenerator(fullFilePath) {
      const filestream = createReadStream(fullFilePath);
      const rl = readline.createInterface({
        input: filestream,
        crlfDelay: Infinity,
      });
      for await (const line of rl) {
        yield line;
      }
    }
    
    (async function test() {
      const gen = lineOfFileGenerator(path.resolve(__dirname, './test.txt'));
      for await (let retVal of gen) {
        console.log(retVal);
      }
      // console.log(await gen.next());
      // console.log(await gen.next());
      // console.log(await gen.next());
      // console.log(await gen.next());
    })();
    

    test.txt:

    line 1
    line 2
    line 3
    

    输出:

    ⚡  node index.js
    line 1
    line 2
    line 3
    

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 2020-08-03
      • 1970-01-01
      • 2020-11-24
      • 2020-03-15
      • 1970-01-01
      • 2020-03-01
      • 2019-10-30
      • 1970-01-01
      相关资源
      最近更新 更多