StoryShots adds automatic Jest Snapshot Testing for Storybook.
To use StoryShots, you must use your existing Storybook stories as the input for Jest Snapshot Testing.
Add the following module into your app.
npm install --save-dev @storybook/addon-storyshots
Usually, you might already have completed this step. If not, here are some resources for you.
If you are using Create React App, it's already configured for Jest. You just need to create a filename with the extension .test.js
.
Otherwise check these links:
- Egghead lesson. paid content
- Official Docs
Note: If you use React 16, you'll need to follow these additional instructions.
StoryShots addon for React is dependent on react-test-renderer, but doesn't install it, so you need to install it separately.
npm install --save-dev react-test-renderer
StoryShots addon for Angular is dependent on jest-preset-angular, but doesn't install it, so you need to install it separately.
npm install --save-dev jest-preset-angular
If you already use Jest for testing your angular app - probably you already have the needed jest configuration. Anyway you can add these lines to your jest config:
module.exports = {
globals: {
__TRANSFORM_HTML__: true,
},
transform: {
'^.+\\.jsx?$': 'babel-jest',
'^.+\\.(ts|html)$': '<rootDir>/node_modules/jest-preset-angular/preprocessor.js',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node', '.html'],
};
StoryShots addon for Vue is dependent on jest-vue-preprocessor, but doesn't install it, so you need to install it separately.
npm install --save-dev jest-vue-preprocessor
If you already use Jest for testing your vue app - probably you already have the needed jest configuration. Anyway you can add these lines to your jest config:
module.exports = {
transform: {
'^.+\\.jsx?$': 'babel-jest',
'.*\\.(vue)$': '<rootDir>/node_modules/jest-vue-preprocessor',
},
transformIgnorePatterns: [
'/node_modules/(?!(@storybook/.*\\.vue$))',
],
moduleFileExtensions: ['vue', 'js', 'jsx', 'json', 'node'],
};
Storyshots addon is currently supporting React, Angular and Vue. Each framework needs its own packages to be integrated with Jest. We don't want people that use only React will need to bring other dependencies that do not make sense for them.
dependencies
- will installed an exact version of the particular dep - Storyshots can work with different versions of the same framework (let's say React v16 and React v15), that have to be compatible with a version of its plugin (react-test-renderer).
optionalDependencies
- behaves like a regular dependency, but do not fail the installation in case there is a problem to bring the dep.
peerDependencies
- listing all the deps in peer will trigger warnings during the installation - we don't want users to install unneeded deps by hand.
optionalPeerDependencies
- unfortunately there is nothing like this =(
For more information read npm docs
Create a new test file with the name Storyshots.test.js
. (Or whatever the name you prefer, as long as it matches Jest's config testMatch
).
Then add following content to it:
import initStoryshots from '@storybook/addon-storyshots';
initStoryshots();
That's all.
Now run your Jest test command. (Usually, npm test
.) Then you can see all of your stories are converted as Jest snapshot tests.
react-test-renderer
doesn't provide refs for rendered components. By
default, it returns null when the refs are referenced. In order to mock
out elements that rely on refs, you will have to use the
createNodeMock
option added to React starting with version 15.4.0.
Here is an example of how to specify the createNodeMock
option in Storyshots:
import initStoryshots, { snapshotWithOptions } from '@storybook/addon-storyshots'
import TextareaThatUsesRefs from '../component/TextareaThatUsesRefs'
initStoryshots({
test: snapshotWithOptions({
createNodeMock: (element) => {
if (element.type === TextareaThatUsesRefs) {
return document.createElement('textarea')
}
},
}),
})
/*\ React-native is not supported by this test function.
Internally, it uses jest-image-snapshot.
When willing to generate and compare image snapshots for your stories, you have two options:
- Have a storybook running (ie. accessible via http(s), for instance using
yarn run storybook
) - Have a static build of the storybook (for instance, using
yarn run build-storybook
)
Then you will need to reference the storybook URL (file://...
if local, http(s)://...
if served)
Then you can either create a new Storyshots instance or edit the one you previously used:
import initStoryshots, { imageSnapshot } from '@storybook/addon-storyshots';
initStoryshots({suite: 'Image storyshots', test: imageSnapshot()});
This will assume you have a storybook running on at http://localhost:6006. Internally here are the steps:
- Browses each stories (calling http://localhost:6006/iframe.html?... URL),
- Take screenshots & save all images under _image_snapshots_ folder.
If you want to set specific storybook URL, you can specify via the storybookUrl
parameter, see below:
import initStoryshots, { imageSnapshot } from '@storybook/addon-storyshots';
initStoryshots({suite: 'Image storyshots', test: imageSnapshot({storybookUrl: 'http://my-specific-domain.com:9010'})});
The above config will use https://my-specific-domain.com:9010 for screenshots.
You may also use a local static build of storybook if you do not want to run the webpack dev-server:
import initStoryshots, { imageSnapshot } from '@storybook/addon-storyshots';
initStoryshots({suite: 'Image storyshots', test: imageSnapshot({storybookUrl: 'file:///path/to/my/storybook-static'})});
If you wish to customize jest-image-snapshot, then you can provide a getMatchOptions
parameter that should return the options config object. Additionally, you can provide beforeScreenshot
which is called before the screenshot is captured.
import initStoryshots, { imageSnapshot } from '@storybook/addon-storyshots';
const getMatchOptions = ({context : {kind, story}, url}) => {
return {
failureThreshold: 0.2,
failureThresholdType: 'percent',
}
}
const beforeScreenshot = (page, {context : {kind, story}, url}) => {
return new Promise(resolve =>
setTimeout(() => {
resolve();
}, 600)
)
}
initStoryshots({suite: 'Image storyshots', test: imageSnapshot({storybookUrl: 'http://localhost:6006', getMatchOptions, beforeScreenshot})});
getMatchOptions
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.
You may want to use another Jest project to run your image snapshots as they require more resources: Chrome and Storybook built/served. You can find a working example of this in the official-storybook example.
Integrate image storyshots with Create React App
You have two options here, you can either:
-
Simply add the storyshots configuration inside any of your
test.js
file. You must ensure you have either a running storybook or a static build available. -
Create a custom test file using Jest outside of the CRA scope:
A more robust approach would be to separate existing test files ran by create-react-app (anything
(test|spec).js
suffixed files) from the test files to run storyshots with image snapshots. This use case can be achieved by using a custom name for the test file, ie something likeimage-storyshots.runner.js
. This file will contains theinitStoryshots
call with image snapshots configuration. Then you will create a separate script entry in your package.json, for instance{ "scripts": { "image-snapshots" : "jest image-storyshots.runner.js --config path/to/custom/jest.config.json" } }
Note that you will certainly need a custom config file for Jest as you run it outside of the CRA scope and thus you do not have the built-in config.
Once that's setup, you can run
yarn run image-snapshots
(ornpm run image-snapshots
).
An image snapshot is simply a screenshot taken by a web browser (in our case, Chrome).
The browser opens a page (either using the static build of storybook or a running instance of Storybook)
If you run your test without either the static build or a running instance, this wont work.
To make sure your screenshots are taken from latest changes of your Storybook, you must keep your static build or running Storybook up-to-date.
This can be achieved by adding a step before running the test ie: yarn run build-storybook && yarn run image-snapshots
.
If you run the image snapshots against a running Storybook in dev mode, you don't have to care about being up-to-date because the dev-server is watching changes and rebuilds automatically.
By default, Storyshots assumes the config directory path for your project as below:
- Storybook for React:
.storybook
- Storybook for React Native:
storybook
If you are using a different config directory path, you could change it like this:
import initStoryshots from '@storybook/addon-storyshots';
initStoryshots({
configPath: '.my-storybook-config-dir'
});
By default, Storyshots groups stories inside a Jest test suite called "Storyshots". You could change it like this:
import initStoryshots from '@storybook/addon-storyshots';
initStoryshots({
suite: 'MyStoryshots'
});
If you'd like to only run a subset of the stories for your snapshot tests based on the story's kind:
import initStoryshots from '@storybook/addon-storyshots';
initStoryshots({
storyKindRegex: /^MyComponent$/
});
This can be useful if you want to separate the snapshots in directories next to each component. See an example here.
If you want to run all stories except stories of a specific kind, you can write an inverse regex which is true for all kinds except those with a specific word such as DontTest
import initStoryshots from '@storybook/addon-storyshots';
initStoryshots({
storyKindRegex:/^((?!.*?DontTest).)*$/
});
This can be useful while testing react components which make use of the findDomNode API since they always fail with snapshot testing while using react-test-renderer see here
If you'd like to only run a subset of the stories for your snapshot tests based on the story's name:
import initStoryshots from '@storybook/addon-storyshots';
initStoryshots({
storyNameRegex: /buttons/
});
If you are running tests from outside of your app's directory, storyshots' detection of which framework you are using may fail. Pass "react"
or "react-native"
to short-circuit this.
Run a custom test function for each story, rather than the default (a vanilla snapshot test). Setting test
will take precedence over the renderer
option. See the exports section below for more details.
Pass a custom renderer (such as enzymes mount
) to record snapshots. Note that setting test
overrides renderer
.
import initStoryshots from '@storybook/addon-storyshots';
import { mount } from 'enzyme';
initStoryshots({
renderer: mount,
});
If you are using enzyme, you need to make sure jest knows how to serialize rendered components.
You can either pass in a serializer (see below) or specify an enzyme-compatible serializer (like enzyme-to-json, jest-serializer-enzyme etc.) as the default snapshotSerializer
in your config.
Example for jest config in package.json
:
"devDependencies": {
"enzyme-to-json": "^3.2.2"
},
"jest": {
"snapshotSerializers": [
"enzyme-to-json/serializer"
]
}
Pass a custom serializer (such as enzyme-to-json) to serialize components to snapshot-comparable data.
import initStoryshots from '@storybook/addon-storyshots';
import toJSON from 'enzyme-to-json';
initStoryshots({
renderer: mount,
serializer: toJSON,
});
This option only needs to be set if the default snapshotSerializers
is not set in your jest config.
Apart from the default export (initStoryshots
), Storyshots also exports some named test functions (see the test
option above):
The default, render the story as normal and take a Jest snapshot.
Just render the story, don't check the output at all (useful if you just want to ensure it doesn't error).
Like the default, but allows you to specify a set of options for the test renderer. See for example here.
Like snapshotWithOptions
, but generate a separate snapshot file for each stories file rather than a single monolithic file (as is the convention in Jest). This makes it dramatically easier to review changes.
This option is useful when running test with multiSnapshotWithOptions(options)
in order to track snapshots are matching the stories. (disabled by default).
The value is just a settings to a glob
object, that searches for the snapshot files.
initStoryshots({
integrityOptions: { cwd: __dirname }, // it will start searching from the current directory
test: multiSnapshotWithOptions({}),
});
Take a snapshot of a shallow-rendered version of the component. Note that this option will be overriden if you pass a renderer
option.
Utility function used in multiSnapshotWithOptions
. This is made available for users who implement custom test functions that also want to take advantage of multi-file storyshots.
Render the story and take Jest snapshots as images. see Configure image snapshots
Let's say we wanted to create a test function for shallow && multi-file snapshots:
import initStoryshots, { getSnapshotFileName } from '@storybook/addon-storyshots';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
initStoryshots({
test: ({ story, context }) => {
const snapshotFileName = getSnapshotFileName(context);
const storyElement = story.render(context);
const shallowTree = shallow(storyElement);
if (snapshotFileName) {
expect(toJson(shallowTree)).toMatchSpecificSnapshot(snapshotFileName);
}
}
});