循环播放链接(故事)并截取屏幕截图

时间:2017-10-24 14:18:24

标签: puppeteer

我在这里尝试做的是循环故事书故事,所以我可以对它们进行视觉回归测试:

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功能是正确的,但随后一切都中断了,我不知道为什么。

有什么想法吗?

1 个答案:

答案 0 :(得分:11)

forEach不适合async-await。请改用for..of

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