Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including @storybook/addon-storyshots with all npm packages installed. Try it out:

var addonStoryshots = require("@storybook/addon-storyshots")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

@storybook/addon-storyshots v5.2.6

StoryShots is a Jest Snapshot Testing Addon for Storybook.


StoryShots adds automatic Jest Snapshot Testing for Storybook.

Framework Support

StoryShots In Action

To use StoryShots, you must use your existing Storybook stories as the input for Jest Snapshot Testing.

Getting Started

Add the following module into your app.

yarn add @storybook/addon-storyshots --dev

Configure your app for Jest

In many cases, for example Create React App, it's already configured for Jest. You just need to create a filename with the extension .test.js.

If you still need to configure jest you can use the resources mentioned below:

Note: If you use React 16, you'll need to follow these additional instructions.

Note: Make sure you have added the json extension to moduleFileExtensions in jest.config.json. If this is missing it leads to the following error: Cannot find module 'spdx-license-ids' from 'scan.js'.

Note: Please make sure you are using jsdom as the testEnvironment on your jest config file.

Configure Jest to work with Webpack's require.context()

Sometimes it's useful to configure Storybook with Webpack's require.context feature. You could be loading stories one of two ways.

  1. If you're using the storiesOf API, you can integrate it this way:
import { configure } from '@storybook/react';

const req = require.context('../stories', true, /\.stories\.js$/); // <- import all the stories at once

function loadStories() {
  req.keys().forEach(filename => req(filename));

configure(loadStories, module);
  1. If you're using Component Story Format (CSF), you'll integrate it like so:
import { configure } from '@storybook/react';

const req = require.context('../stories', true, /\.stories\.js$/); // <- import all the stories at once

configure(req, module);

The problem here is that it will work only during the build with webpack, other tools may lack this feature. Since Storyshot is running under Jest, we need to polyfill this functionality to work with Jest. The easiest way is to integrate it to babel.

You can do this with a Babel plugin or macro. If you're using create-react-app (v2 or above), use the macro.

Option 1: Plugin

First, install it:

yarn add babel-plugin-require-context-hook --dev

Next, it needs to be registered and loaded before each test. To register it, create a file with the following register function .jest/register-context.js:

import registerRequireContextHook from 'babel-plugin-require-context-hook/register';

That file needs to be added as a setup file for Jest. To do that, add (or create) a property in Jest's config called setupFiles. Add the file name and path to this array.

setupFiles: ['<rootDir>/.jest/register-context.js']

Finally, add the plugin to .babelrc:

  "presets": ["..."],
  "plugins": ["..."],
  "env": {
    "test": {
      "plugins": ["require-context-hook"]

The plugin is only added to the test environment otherwise it could replace webpack's version of it.

Option 2: Macro

First, install it:

yarn add require-context.macro --dev

Now, inside of your Storybook config file, simply import the macro and run it in place of require.context, like so:

import requireContext from 'require-context.macro';

// const req = require.context('../stories', true, /\.stories\.js$/); <-- replaced
const req = requireContext('../stories', true, /\.stories\.js$/);

Configure Jest for React

StoryShots addon for React is dependent on react-test-renderer, but doesn't install it, so you need to install it separately.

yarn add react-test-renderer --dev

Configure Jest for Angular

StoryShots addon for Angular is dependent on jest-preset-angular, but doesn't install it, so you need to install it separately.

yarn add 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?apos;: 'babel-jest',
    '^.+\\.(ts|html)apos;: '<rootDir>/node_modules/jest-preset-angular/preprocessor.js',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node', '.html'],

Configure Jest for Vue

StoryShots addon for Vue is dependent on jest-vue-preprocessor, but doesn't install it, so you need to install it separately.

yarn add 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?apos;: 'babel-jest',
    '.*\\.(vue)apos;: '<rootDir>/node_modules/jest-vue-preprocessor',
  transformIgnorePatterns: [
  moduleFileExtensions: ['vue', 'js', 'jsx', 'json', 'node'],

Configure Jest for Preact

StoryShots addon for Preact is dependent on preact-render-to-json, but doesn't install it, so you need to install it separately.

yarn add preact-render-to-json --dev

Why don't we install dependencies of each framework ?

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

Configure Storyshots for HTML snapshots

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';


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.


Using createNodeMock to mock refs

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'

  test: snapshotWithOptions({
    createNodeMock: (element) => {
      if (element.type === TextareaThatUsesRefs) {
        return document.createElement('textarea')

Provide a function to have story-specific options:

  test: snapshotWithOptions(story =>({
    createNodeMock: (element) => {
      if( == 'foobar') {
        return null
      return element

StoryShots for async rendered components

You can make use of Jest done callback to test components that render asynchronously. This callback is passed as param to test method passed to initStoryshots(...) when the asyncJest option is given as true.


The following example shows how we can use the done callback to take StoryShots of a Relay component. Each kind of story is written into its own snapshot file with the use of getSnapshotFileName.

Add stories of UserForm in the file: UserForm.story.jsx

/* global module */
import React from "react";
import { QueryRenderer } from "react-relay";
import { storiesOf } from "@storybook/react";

// Use the same queries used in YOUR app routes
import { newUserFormQuery, editUserFormQuery } from "app/routes";
import UserFormContainer from "app/users/UserForm";

// YOUR function to generate a Relay Environment mock.
// See for more info
import getEnvironment from "test/support/relay-environment-mock";

// User test data YOU generated for your tests
import { user } from "test/support/data/index";

// Use this function to return a new Environment for each story
const Environment = () =>
    mocks: {
      Node: () => ({ __typename: "User" }),
      User: () => user


  NOTICE that the QueryRenderer render its children via its render props.

  If we don't take the StoryShot async then we will only see the QueryRenderer in the StoryShot.

  The following QueryRenderer returns null in the first render (it can be a loading indicator instead in real file) and then when it gets the data to respond to query, it renders again with props containing the data for the Component
const renderStory = (query, environment, variables = {}) => (
    render={({ props, error }) => {
      if (error) {
      } else if (props) {
        return <UserFormContainer {...props} />;
      return null;

storiesOf("users/UserForm", module)
  .add("New User", () => {
    const environment = new Environment();
    return renderStory(newUserFormQuery, environment);
  .add("Editing User", () => {
    const environment = new Environment();
    return renderStory(editUserFormQuery, environment, { id: });

Then, init Storyshots for async component in the file: StoryShots.test.js

import initStoryshots, { Stories2SnapsConverter } from "@storybook/addon-storyshots";
import { mount } from "enzyme";
import toJson from "enzyme-to-json";

// Runner
  asyncJest: true, // this is the option that activates the async behaviour
  test: ({
    done // --> callback passed to test method when asyncJest option is true
  }) => {
    const converter = new Stories2SnapsConverter();
    const snapshotFilename = converter.getSnapshotFileName(context);
    const storyElement = story.render();

    // mount the story
    const tree = mount(storyElement);

    // wait until the mount is updated, in our app mostly by Relay
    // but maybe something else updating the state of the component
    // somewhere
    const waitTime = 1;
    setTimeout(() => {
      if (snapshotFilename) {

    }, waitTime)
  // other options here

NOTICE that When using the asyncJest: true option, you also must specify a test method that calls the done() callback.

This is a really powerful technique to write stories of Relay components because it integrates data fetching with component rendering. So instead of passing data props manually, we can let Relay do the job for us as it does in our application.

Whenever you change you're data requirements by adding (and rendering) or (accidentally) deleting fields in your graphql query fragments, you'll get a different snapshot and thus an error in the StoryShot test.



The config parameter must be a function that helps to configure storybook like the config.js does. If it's not specified, storyshots will try to use configPath parameter.

import initStoryshots from '@storybook/addon-storyshots';

  config: ({ configure }) =>
    configure(() => {
    }, module),


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';

  configPath: '.my-storybook-config-dir'

Or, as a more complex example, if we have a package in our lerna project called app with the path ./packages/app/src/__tests__/storsyhots.js and the storybook config directory ./packages/app/.storybook:

import path from 'path';
import initStoryshots from '@storybook/addon-storyshots';

initStoryshots({ configPath: path.resolve(__dirname, '../../.storybook') });

configPath can also specify path to the config.js itself. In this case, config directory will be a base directory of the configPath. It may be useful when the config.js for test should differ from the original one. It also may be useful for separating tests to different test configs:

  configPath: '.my-storybook-config-dir/testConfig1.js'

  configPath: '.my-storybook-config-dir/testConfig2.js'


By default, Storyshots groups stories inside a Jest test suite called "Storyshots". You could change it like this:

import initStoryshots from '@storybook/addon-storyshots';

  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';

  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';


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';

  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. You can still overwrite what renderer is used for the test function:

import initStoryshots, { renderWithOptions } from '@storybook/addon-storyshots';
import { mount } from 'enzyme';

  test: renderWithOptions({
    renderer: mount,


Pass a custom renderer (such as enzymes mount) to record snapshots. This may be necessary if you want to use React features that are not supported by the default test renderer, such as ref or Portals. Note that setting test overrides renderer.

import initStoryshots from '@storybook/addon-storyshots';
import { mount } from 'enzyme';

  renderer: mount,

If you are using enzyme, you need to make sure jest knows how to serialize rendered components. For that, you can pass an enzyme-compatible snapshotSerializer (like enzyme-to-json, jest-serializer-enzyme etc.) with the snapshotSerializer option (see below).


Pass an array of snapshotSerializers to the jest runtime that serializes your story (such as enzyme-to-json).

import initStoryshots from '@storybook/addon-storyshots';
import { createSerializer } from 'enzyme-to-json';

  renderer: mount,
  snapshotSerializers: [createSerializer()],

This option needs to be set if either:

  • the multiSnapshot function is used to create multiple snapshot files (i.e. one per story), since it ignores any serializers specified in your jest config.
  • serializers not specified in your jest config should be used when snapshotting stories.

serializer (deprecated)

Pass a custom serializer (such as enzyme-to-json) to serialize components to snapshot-comparable data. The functionality of this option is completely covered by snapshotSerializers which should be used instead.

import initStoryshots from '@storybook/addon-storyshots';
import toJSON from 'enzyme-to-json';

  renderer: mount,
  serializer: toJSON,

This option only needs to be set if the default snapshotSerializers is not set in your jest config.


This parameter should be an instance of the Stories2SnapsConverter (or a derived from it) Class that is used to convert story-file name to snapshot-file name and vice versa.

By default, the instance of this class is created with these default options:

  snapshotsDirName: '__snapshots__',
  snapshotExtension: '.storyshot',
  storiesExtensions: ['.js', '.jsx', '.ts', '.tsx'],

This class might be overridden to extend the existing conversion functionality or instantiated to provide different options:

import initStoryshots, { Stories2SnapsConverter } from '@storybook/addon-storyshots';

  stories2snapsConverter: new Stories2SnapsConverter({
    snapshotExtension: '.storypuke',
    storiesExtensions: ['.foo'],


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. This is useful as a low-effort way of smoke testing your components to ensure they do not error.


Like the default, but allows you to specify a set of options for the test renderer. See for example here.


Like the default, but allows you to specify a set of options for the renderer, just like snapshotWithOptions.


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. If you'd like the benefit of separate snapshot files, but don't have custom options to pass, simply pass an empty object. If you use Component Story Format, you may also need to add an additional Jest transform to automate detecting story file names:

// jest.config.js
module.exports = {
  transform: {
    '^.+\\.stories\\.jsx?apos;: '@storybook/addon-storyshots/injectFileName',
    '^.+\\.jsx?apos;: 'babel-jest',


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.

  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 overridden if you pass a renderer option.


This is a class that generates snapshot's name based on the story (kind, story & filename) and vice versa.


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';

  test: ({ story, context }) => {
    const snapshotFileName = getSnapshotFileName(context);
    const storyElement = story.render();
    const shallowTree = shallow(storyElement);

    if (snapshotFileName) {


Enables Jest done() callback in the StoryShots tests for async testing. See StoryShots for async rendered components for more info.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free