Looping through links(stories) and taking screenshots

五迷三道 提交于 2019-12-07 03:59:24

问题


What I'm trying to do here is loop through Storybook stories so I can perform visual regression testing on them:

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();
});

One problem is that I get this because of the await broswer.close() that isn't waiting for everything to finish:

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>

This happens for each storyLink except the first.

If I comment out the await browser.close() line, the screenshots are being taken, but not in the expected wait. Instead of each story having one screenshot, the last story is being screenshotted for the amount of stories. For example, I've got 4 stories in total, but I will have 4 screenshots of the last story instead of one for each story.

I don't understand why this behaviour is happening. The storyLinks returned from the page.evaluate funtions are correct, but then everything breaks and I've got no idea why.

Any ideas?


回答1:


forEach is not good for async-await. Use for..of instead,

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


来源:https://stackoverflow.com/questions/46912940/looping-through-linksstories-and-taking-screenshots

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!