Skip to content

Instantly share code, notes, and snippets.

@PaulieScanlon
Last active September 18, 2020 16:54
Show Gist options
  • Save PaulieScanlon/9aa064dcec0565a14d8db5f48d26515d to your computer and use it in GitHub Desktop.
Save PaulieScanlon/9aa064dcec0565a14d8db5f48d26515d to your computer and use it in GitHub Desktop.
// button.stories.tsx
import React from 'react'
import { Button } from '.'
export default {
title: 'components/Button',
parameters: {
component: Button,
componentSubtitle: 'The Button component is of html type button',
},
}
export const Usage = () => <Button>Button</Button>
// button.test.ts
import React from 'react'
import { render, screen } from '@testing-library/react'
import { Usage } from './Button.stories'
import { Button } from './Button'
describe('<Button />', () => {
test("it renders it's children (story version)", () => {
// Use the tesing libray render method to render the Usage story
render(Usage())
const button = screen.getByTestId('my-button')
expect(button.children).toBeDefined()
})
test("it renders it's children (repeated version)", () => {
// Use the tesing libray render method to render the component, but you have to import it - annoying
render(<Button>some child</Button>)
const button = screen.getByTestId('my-button')
expect(button.children).toBeDefined()
})
})
@PaulieScanlon
Copy link
Author

The "theory" if you like is to create a story for every state the component can be in. Button for example might have different styles when it's disabled, or if it's got a prop called variant etc.

If you import each story has i've done with Usage you can be sure you have a test for every visual state the component can be in which remains in sync with the stories you create in Storybook.

If you need to you can of course import the component and use the render method to render it. You may have to do this if you want to test a callback, onClick for example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment