Skip to content

Instantly share code, notes, and snippets.

@og24715
Last active May 23, 2022 07:15
Show Gist options
  • Save og24715/a500a1796c0208e3018f8e7d68bdeaa5 to your computer and use it in GitHub Desktop.
Save og24715/a500a1796c0208e3018f8e7d68bdeaa5 to your computer and use it in GitHub Desktop.
Interaction testing in Storybook play function and, reuse to assert in Jest
import { composeStories } from '@storybook/testing-react';
import { render } from '@testing-library/react';
import * as stories from './Counter.stories';
const { ClickOnce, ClickTwice } = composeStories(stories);
test('Click once', () => {
const { container, getByRole } = render(<ClickOnce />);
ClickOnce.play({ canvasElement: container });
expect(getByRole<HTMLInputElement>('spinbutton').value).toBe('1');
});
test('Click twice', () => {
const { container, getByRole } = render(<ClickTwice />);
ClickTwice.play({ canvasElement: container });
expect(getByRole<HTMLInputElement>('spinbutton').value).toBe('2');
});
import type { ComponentMeta, ComponentStoryObj } from '@storybook/react';
import { fireEvent, within } from '@storybook/testing-library';
import { Counter } from './Counter';
export default {
title: 'counter',
component: Counter,
} as ComponentMeta<typeof Counter>;
type Story = ComponentStoryObj<typeof Counter>;
export const ClickOnce: Story = {
play({ canvasElement }) {
const canvas = within(canvasElement);
fireEvent.click(canvas.getByRole('button'));
},
};
export const ClickTwice: Story = {
play(context) {
ClickOnce.play!(context);
ClickOnce.play!(context);
},
};
import type { ReactElement } from 'react';
import { useState } from 'react';
export function Counter(): ReactElement {
const [counter, setCounter] = useState(0);
return (
<div>
<input type="number" readOnly value={counter} />
<button
type="button"
onClick={() => {
setCounter(v => v + 1);
}}
>
+
</button>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment