Skip to content

Instantly share code, notes, and snippets.

@lifeiscontent lifeiscontent/
Last active Mar 23, 2020

What would you like to do?
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:

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';
describe('ArticleDeleteButton', () => {
it('does not render with insufficient access', () => {
render(decorateStory(renders, story));
const button = screen.queryByText('Delete Article');
it('calls onDelete on click', async () => {
render(decorateStory(canDelete, story));
const button = await screen.findByText('Delete Article');;
// 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
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
You can’t perform that action at this time.