繁体   English   中英

操纵up的异步功能,但会在测试中引发错误

[英]Puppeteer async function that works but raises error in test

我正在尝试使用Chai.js测试异步功能。 当我从程序中调用它时,它可以工作,但是在测试时,它返回未定义的。

这是功能

async function getLinks(url, minW = 1, minH = 1) {
  try {
    const pup = await puppeteer.launch({ defaultViewport: null });
    let page = await pup.newPage();

    await page.goto(url, { waitUntil: 'networkidle2' });

    return await page.evaluate(
      ({ minW, minH }) => {
        return [...document.getElementsByTagName('a')]
          .map(x => {
            return { url: x.href, type: 'a' };
          })
          .concat(
            [...document.getElementsByTagName('img')]
              .filter(x => x.naturalWidth >= minW && x.naturalHeight >= minH)
              .map(x => {
                return { url: x.src, type: 'img' };
              })
          );
      },
      { minW, minH }
    );
  } catch (err) {
    console.log(err);
  }
}

这是测试

describe('getLinks', () => {
    it('should return an array of links.', async function() {
      const links = await getLinks('http://www.msftconnecttest.com');
      expect(links).to.be.an('array');
    }).timeout(5000);
  });

而且,这是我得到的错误

1) getLinks
       should return an array of links.:
     AssertionError: expected undefined to be an array
      at Context.<anonymous> (test\test.js:9:27)
      at processTicksAndRejections (internal/process/task_queues.js:82:5)

更新
代码落入catch块,这是原始错误消息:

Error: Evaluation failed: ReferenceError: cov_1xrphtbyiu is not defined
    at __puppeteer_evaluation_script__:1:18
      at ExecutionContext._evaluateInternal (node_modules\puppeteer\lib\ExecutionContext.js:122:13)
      at processTicksAndRejections (internal/process/task_queues.js:82:5)
      at async ExecutionContext.evaluate (node_modules\puppeteer\lib\ExecutionContext.js:48:12)
      at async getLinks (main.js:1:6360)
      at async Context.<anonymous> (test\test.js:8:21)

我不知道它变得有问题的原因,因为我没有使用Babel或类似的工具,但是在我更改了return代码后,现在它在测试和程序中都可以使用。

这可能是特定于版本的问题。

return await page.evaluate(
      `((minW, minH) => {
        return [...document.getElementsByTagName('a')]
          .map(x => {
            return { url: x.href, type: 'a' };
          })
          .concat(
            [...document.getElementsByTagName('img')]
              .filter(x => x.naturalWidth >= minW && x.naturalHeight >= minH)
              .map(x => {
                return { url: x.src, type: 'img' };
              })
          );
      })(${minW}, ${minH})`,
    );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM