StoryShot Snapshot Tests with StoryBook - Tuong-Nguyen/JavaScript-Structure GitHub Wiki
Jest Snapshot Testing
- Snapshot = picture of a component with some props
import React from 'react'
import renderer from 'react-test-renderer'
import TodoTextInput from './TodoTextInput'
test('snapshots are awesome', () => {
// Render the component
const component = renderer.create(
<TodoTextInput onSave={() => {}} />
);
// Output the snapshot
const tree = component.toJSON();
// Assert with saved snapshot
expect(tree).toMatchSnapshot();
}
- Snapshot of previous component:
{
type: 'input',
props:
{
className: '',
type: 'text',
placeholder: undefined,
autoFocus: 'true',
value: '',
onBlur: [Function],
onChange: [Function],
onKeyDown: [Function] },
children: null
}
}
- Snapshot is saved in
__snapshot__
folder - When running the test, the test can fail because:
- Component is changed and breaks the test: unexpected -> fix the component
- Component is updated: expected -> update the new snapshot (
npm test -- -u
)
Storybook - Storyshots
https://github.com/storybooks/storybook/tree/master/addons/storyshots
Storyshots add-on of Storybook will generates Snapshot tests for stories in storybook.
Setup
npm install jest-cli jest --save-dev
npm install --save-dev @storybook/addon-storyshots
- Add a test file with name: Storyshots.test.js
import initStoryshots from '@storybook/addon-storyshots';
initStoryshots();
Run test with npm test