Skip to content

Instantly share code, notes, and snippets.

@lifeiscontent
Last active March 23, 2020 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lifeiscontent/ef864df93cc798d27753383268171fcc to your computer and use it in GitHub Desktop.
Save lifeiscontent/ef864df93cc798d27753383268171fcc to your computer and use it in GitHub Desktop.
Action Mocking in Jest

Action Mocking in Jest with Storybook.

This describes how to use storybook stories as fixtures in jest, and how to mock action to test behavior in the story.

Link to full example: https://github.com/lifeiscontent/realworld

export const action = jest.fn();
const actions = {};
action.mockImplementation(name => {
// if we haven't see the action name before, store it
if (actions[name] == null) {
actions[name] = jest.fn();
}
// return the mock function for the name
return actions[name];
});
import { render, screen, fireEvent } from '@testing-library/react';
import { action } from '@storybook/addon-actions';
import story, { renders, canDelete } from './index.stories';
import { decorateStory } from '../../utils/storybook';
jest.mock('@storybook/addon-actions');
describe('ArticleDeleteButton', () => {
it('does not render with insufficient access', () => {
render(decorateStory(renders, story));
const button = screen.queryByText('Delete Article');
expect(button).toBeNull();
});
it('calls onDelete on click', async () => {
render(decorateStory(canDelete, story));
const button = await screen.findByText('Delete Article');
fireEvent.click(button);
// since we have our addon-actions mock setup, we can test that `action('onDelete')` was called
// because in the test environment it always results in the same function reference
expect(action('onDelete')).toHaveBeenCalled();
});
});
import { defaultDecorateStory } from '@storybook/client-api';
export function decorateStory(example, story) {
return defaultDecorateStory(example, story.decorators ?? [])(example.story);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment