Skip to content

Instantly share code, notes, and snippets.

@andyrichardson
Last active November 17, 2020 11:10
Show Gist options
  • Save andyrichardson/beea4d328dd878c0360ea31413e6f99c to your computer and use it in GitHub Desktop.
Save andyrichardson/beea4d328dd878c0360ea31413e6f99c to your computer and use it in GitHub Desktop.
Example approach for testing storybook fixtures in jest.

About

Here's a quick example of how to get a 1-1 reproduction of storybook fixtures in jest.

Note: If you use storybook, definitely do this - it removes the need to set up context manually for jest testing

Create a providing component for jest

// .storybook/preview.tsx

//...

/** All our decorators combined for testing. */
export const StoryDecorator: FC = ({ children }) => {
  // Ensure single child
  if (Array.isArray(children) || !children) {
    throw Error('StoryDecorator must have only one child element (a fixture)');
  }

  // Ensure child is story
  if (typeof children !== 'object') {
    throw Error('StoryDecorator expects a fixture child component');
  }

  // Merge current story context with default story context shape
  const storyContext = (children as any).type || {};
  const context = {
    ...storyContext,
    parameters: {
      ...storyContext.parameters,
    },
  };

  // Compose decorators
  return [decoratorA, decoratorB, decoratorC].reduce(
    (story, decorator) => decorator(() => story, context),
    <>{children}</>,
  );
};

Test fixtures

// MyComponent.spec.tsx
import { mount } from 'enzyme';
import React from 'react';
import { Fetching, Errored, Response } from './MyComponent.stories.tsx';
import { StoryDecorator } from '.storybook/parameters.tsx';

describe("on fetching state", () => {
  it("matches snapshot", () => {
    const wrapper = mount(
      <StoryDecorator>
       <Fetching />
      </StoryDecorator>
    )
    expect(wrapper).toMatchSnapshot();
  })
})

describe("on error state", () => {
  it("matches snapshot", () => {
    const wrapper = mount(
      <StoryDecorator>
       <Errored />
      </StoryDecorator>
    )
    expect(wrapper).toMatchSnapshot();
  })
})

describe("on response state", () => {
  it("matches snapshot", () => {
    const wrapper = mount(
      <StoryDecorator>
       <Errored />
      </StoryDecorator>
    )
    expect(wrapper).toMatchSnapshot();
  })
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment