puppeteer - 遍历链接(故事)并截取屏幕截图

标签 puppeteer

我要在这里做的是遍历Storybook故事,以便可以对它们进行视觉回归测试:

const puppeteer = require('puppeteer');
const { toMatchImageSnapshot } = require('jest-image-snapshot');
expect.extend({ toMatchImageSnapshot });

test('no visual regression for button', async () => {
  const selector = 'a[href*="?selectedKind=Buttons&selectedStory="]';
  const browser = await puppeteer.launch({headless:false, slowMo: 350});
  const page = await browser.newPage();
  await page.goto('http://localhost:8080');


const storyLinks = await page.evaluate(() => {
  const stories = Array.from(document.querySelectorAll('a[href*="?selectedKind=Buttons&selectedStory="]'));
  const links = stories.map(story => story.href);
  return links;
});
 await storyLinks.forEach( (storyLink) => {
   page.goto(storyLink).then(async (res,rej) => {
     const screen = await page.screenshot();
     return await expect(screen).toMatchImageSnapshot();
   });
 });

 await browser.close();
});

一个问题是,由于await broswer.close()并没有等待所有操作完成,所以我得到了这个:
Protocol error (Page.navigate): Target closed.

      at Session._onClosed (../../node_modules/puppeteer/lib/Connection.js:209:23)
      at Connection._onClose (../../node_modules/puppeteer/lib/Connection.js:116:15)
      at Connection.dispose (../../node_modules/puppeteer/lib/Connection.js:121:10)
      at Browser.close (../../node_modules/puppeteer/lib/Browser.js:60:22)
      at Object.<anonymous>.test (__tests__/visual.spec.js:24:16)
          at <anonymous>

除了第一个以外,每个storyLink都会发生这种情况。

如果我将await browser.close()行注释掉,则表示正在截屏,但没有等待。不是每个故事都有一个屏幕截图,而是针对故事的数量对最后一个故事进行屏幕截图。例如,我总共有4个故事,但是我将拥有最后一个故事的4个屏幕截图,而不是每个故事一个。

我不明白为什么会发生这种现象。页面返回的storyLinks.evaluate函数是正确的,但是随后一切都中断了,我也不知道为什么。

有任何想法吗?

最佳答案

forEach不适合异步等待。请改用for..of

for (let storyLink of storyLinks) {
        await page.goto(storyLink)
        const screen = await page.screenshot();
        await expect(screen).toMatchImageSnapshot();
};

关于puppeteer - 遍历链接(故事)并截取屏幕截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46912940/

相关文章:

jestjs - 如何在 jest-puppeteer 中运行特定的测试套件

node.js - 在Ubuntu Server上 puppeteer/ Chrome 失败

Puppeteer - 如何填写 iframe 内的表单?

javascript - 等待过渡在 puppeteer 操作中结束

javascript - 如果存在则单击按钮,否则单击 puppeteer 中的不同按钮

javascript - 抓取 : Only first images are scraped, 其余部分用占位符填充。为什么?

javascript - Puppeteer:如何监听对象事件

chromium - Chromium headless 在 Windows Server Core 2016 上工作吗?

javascript - Puppeteer JS 等待能够选择多个下拉列表

javascript - Puppeteer 在 headless 模式下挂起