Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through links(stories) and taking screenshots

Tags:

puppeteer

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?

like image 566
Ruxandra Anghel Avatar asked Oct 24 '17 14:10

Ruxandra Anghel


1 Answers

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();
};
like image 78
Md. Abu Taher Avatar answered Jan 16 '23 23:01

Md. Abu Taher