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
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); | |
} |