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
// .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}</>,
);
};// 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();
})
})