将 Jest 与 Puppeteer 一起使用:评估失败:ReferenceError:cov_4kq3tptqc 未定义

Ele*_*ena 9 javascript automated-tests web-scraping jestjs puppeteer

我正在尝试使用 Puppeteer 获取页面的描述,我有一个高阶函数,可以为该函数提供页面对象:

export const checkDescription = async page => {
  const metaDescription = await page.$eval(
    'meta[name="description"]',
    description => description.getAttribute("content")
  );
  return metaDescription;
};
Run Code Online (Sandbox Code Playgroud)

该功能按预期工作。然后,我使用 Jest 运行测试。

const testDescription = await withPage(checkDescription)(URL);
expect(typeof testDescription).toBe("string");
Run Code Online (Sandbox Code Playgroud)

我有以下错误:

  Error: Evaluation failed: ReferenceError: cov_4kq3tptqc is not defined
      at __puppeteer_evaluation_script__:2:41
      at ExecutionContext.evaluateHandle 
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)
    -- ASYNC --
      at ExecutionContext.<anonymous> 
      at ExecutionContext.evaluate
      at ExecutionContext.<anonymous> 
      at ElementHandle.$eval
      at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)
    -- ASYNC --
Run Code Online (Sandbox Code Playgroud)

如果我只是将该函数粘贴到 jest 文件中,那么它会按预期工作

小智 6

如果您需要收集覆盖率,可以通过/* istanbul ignore next */在浏览器之前添加上下文函数(带有 的行.eval)来修复它,以防止伊斯坦布尔覆盖率注入。

  • 这应该是正确的答案 (2认同)

Ele*_*ena 5

在 puppeteer 中,在运行测试时,istanbul 插入了以下内容:

 /* istanbul ignore next */cov_4kq3tptqc.f[7]++;
                    cov_4kq3tptqc.s[19]++;
Run Code Online (Sandbox Code Playgroud)

通过添加config.collectCoverage = false;jest.config