Allow taking a screenshot of just a specific element

This commit is contained in:
StephanBijzitter 2020-09-11 20:42:49 +02:00
parent 0059352ebc
commit e48ad84e1b
3 changed files with 17 additions and 4 deletions

View File

@ -305,3 +305,16 @@ initStoryshots({
```
`getScreenshotOptions` receives an object `{ context: {kind, story}, url}`. _kind_ is the kind of the story and the _story_ its name. _url_ is the URL the browser will use to screenshot.
To create a screenshot of just a single element (with its children), rather than the page or current viewport, an ElementHandle can be returned from `beforeScreenshot`:
```js
import initStoryshots from '@storybook/addon-storyshots';
import { imageSnapshot } from '@storybook/addon-storyshots-puppeteer';
const beforeScreenshot = (page) => page.$('#root > *');
initStoryshots({
suite: 'Image storyshots',
test: imageSnapshot({ storybookUrl: 'http://localhost:6006', beforeScreenshot }),
});
```

View File

@ -1,5 +1,5 @@
import { MatchImageSnapshotOptions } from 'jest-image-snapshot';
import { Base64ScreenShotOptions, Browser, DirectNavigationOptions, Page } from 'puppeteer';
import { Base64ScreenShotOptions, Browser, DirectNavigationOptions, Page, ElementHandle } from 'puppeteer';
export interface Context {
kind: string;
@ -33,7 +33,7 @@ export interface PuppeteerTestConfig extends CommonConfig {
export interface ImageSnapshotConfig extends CommonConfig {
getMatchOptions: (options: Options) => MatchImageSnapshotOptions;
getScreenshotOptions: (options: Options) => Base64ScreenShotOptions;
beforeScreenshot: (page: Page, options: Options) => void;
beforeScreenshot: (page: Page, options: Options) => void | ElementHandle;
afterScreenshot: (options: { image: string; context: Context }) => void;
}

View File

@ -12,8 +12,8 @@ export const imageSnapshot = (customConfig: Partial<ImageSnapshotConfig> = {}) =
...config,
async testBody(page, options) {
expect.assertions(1);
await beforeScreenshot(page, options);
const image = await page.screenshot(getScreenshotOptions(options));
const element = await beforeScreenshot(page, options);
const image = await (element || page).screenshot(getScreenshotOptions(options));
await afterScreenshot({ image, context: options.context });
expect(image).toMatchImageSnapshot(getMatchOptions(options));
},