diff --git a/.storybook/test-runner.ts b/.storybook/test-runner.ts index 0676b452..bbe049e8 100644 --- a/.storybook/test-runner.ts +++ b/.storybook/test-runner.ts @@ -1,5 +1,5 @@ import { toMatchImageSnapshot } from 'jest-image-snapshot'; -import { getStoryContext } from '../dist/playwright/hooks'; +import { getStoryContext, waitForPageReady } from '../dist/playwright/hooks'; import type { TestRunnerConfig } from '../dist'; const snapshotsDir = process.env.SNAPSHOTS_DIR || '__snapshots__'; @@ -22,6 +22,8 @@ const config: TestRunnerConfig = { return; } + await waitForPageReady(page); + // Visual snapshot tests const image = await page.screenshot({ fullPage: true }); expect(image).toMatchImageSnapshot({ diff --git a/README.md b/README.md index 7716f97d..a08ccac4 100644 --- a/README.md +++ b/README.md @@ -559,6 +559,7 @@ Here's a slightly different recipe for image snapshot testing: ```js // .storybook/test-runner.js +const { waitForPageReady } = require('@storybook/test-runner'); const { toMatchImageSnapshot } = require('jest-image-snapshot'); const customSnapshotsDir = `${process.cwd()}/__snapshots__`; @@ -568,6 +569,9 @@ module.exports = { expect.extend({ toMatchImageSnapshot }); }, async postRender(page, context) { + // use the test-runner utility to wait for fonts to load, etc. + await waitForPageReady(page); + // If you want to take screenshot of multiple browsers, use // page.context().browser().browserType().name() to get the browser name to prefix the file name const image = await page.screenshot(); diff --git a/src/playwright/hooks.ts b/src/playwright/hooks.ts index b5e7a48c..c082aa28 100644 --- a/src/playwright/hooks.ts +++ b/src/playwright/hooks.ts @@ -46,3 +46,10 @@ export const getStoryContext = async (page: Page, context: TestContext): Promise storyId: context.id, }); }; + +export const waitForPageReady = async (page: Page) => { + await page.waitForLoadState('domcontentloaded'); + await page.waitForLoadState('load'); + await page.waitForLoadState('networkidle'); + await page.evaluate(() => document.fonts.ready); +};