Last active
May 23, 2022 07:15
-
-
Save og24715/a500a1796c0208e3018f8e7d68bdeaa5 to your computer and use it in GitHub Desktop.
Interaction testing in Storybook play function and, reuse to assert in Jest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}, | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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