我要在这里做的是遍历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/