-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
React: Add testing utilities #12959
Closed
Closed
React: Add testing utilities #12959
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
feae6bc
feat(react): add composeStory utility
yannbf 88b1fb3
feat(examples): add test example with composeStory
yannbf 3ece832
types: update base story to include old story format
yannbf 66fa05e
refactor(react): change composeStory signature
yannbf 23e971c
fix: update type definitions
yannbf dd0e8a3
fix(react): set correct decorator order
yannbf cece749
fix(react): improve docs and types of composeStories
yannbf 4a533f6
deps(react): move @storybook/client-api as dependency
yannbf d7cfac1
chore(react-ts-example): add strictBindCallApply to tsconfig
yannbf 4213a62
chore(react): remove babel proposal
yannbf 4f020a3
chore(react-ts-example): use decorator type in preview
yannbf 44f0477
docs(react): add section about testing utility
yannbf da380b0
fix(react): only support new story type in testing utility
yannbf 9c039d8
docs(react): update testing utility description
yannbf 223787e
docs(react): set globalConfig as default in jsdoc for composeStories
yannbf 7ff68ac
feat(react): configure globalConfig only once in setup files
yannbf fbbd0a3
chore(react-ts-example): update tests to the new syntax with setup files
yannbf 7ecc75b
docs(react): update testing utility guide
yannbf File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
import { defaultDecorateStory, combineParameters } from '@storybook/client-api'; | ||
import { GlobalConfig, Meta, Story, StoryContext } from './types-6-0'; | ||
|
||
let globalStorybookConfig = {}; | ||
|
||
/** Function that sets the globalConfig of your storybook. The global config is the preview module of your .storybook folder. | ||
* | ||
* It should be run a single time, so that your global config (e.g. decorators) is applied to your stories when using `composeStories` or `composeStory`. | ||
* | ||
* Example: | ||
*```jsx | ||
* // setup.js (for jest) | ||
* import { setGlobalConfig } from '@storybook/react'; | ||
* import * as globalStorybookConfig from './.storybook/preview'; | ||
* | ||
* setGlobalConfig(globalStorybookConfig); | ||
*``` | ||
* | ||
* @param config - e.g. (import * as globalConfig from '../.storybook/preview') | ||
*/ | ||
export function setGlobalConfig(config: GlobalConfig) { | ||
globalStorybookConfig = config; | ||
} | ||
|
||
/** | ||
* Function that will receive a story along with meta (e.g. a default export from a .stories file) | ||
* and optionally a globalConfig e.g. (import * from '../.storybook/preview) | ||
* and will return a composed component that has all args/parameters/decorators/etc combined and applied to it. | ||
* | ||
* | ||
* It's very useful for reusing a story in scenarios outside of Storybook like unit testing. | ||
* | ||
* Example: | ||
*```jsx | ||
* import { render } from '@testing-library/react'; | ||
* import { composeStory } from '@storybook/react'; | ||
* import Meta, { Primary as PrimaryStory } from './Button.stories'; | ||
* | ||
* const Primary = composeStory(PrimaryStory, Meta); | ||
* | ||
* test('renders primary button with Hello World', () => { | ||
* const { getByText } = render(<Primary>Hello world</Primary>); | ||
* expect(getByText(/Hello world/i)).not.toBeNull(); | ||
* }); | ||
*``` | ||
* | ||
* @param story | ||
* @param meta - e.g. (import Meta from './Button.stories') | ||
* @param [globalConfig] - e.g. (import * as globalConfig from '../.storybook/preview') this can be applied automatically if you use `setGlobalConfig` in your setup files. | ||
*/ | ||
export function composeStory<GenericArgs>( | ||
story: Story<GenericArgs>, | ||
meta: Meta, | ||
globalConfig: GlobalConfig = globalStorybookConfig | ||
) { | ||
const finalStoryFn = (context: StoryContext) => { | ||
const { passArgsFirst = true } = context.parameters; | ||
if (!passArgsFirst) { | ||
throw new Error( | ||
'composeStory does not support legacy style stories (with passArgsFirst = false).' | ||
); | ||
} | ||
return story(context.args as GenericArgs, context); | ||
}; | ||
|
||
const combinedDecorators = [ | ||
...(story.decorators || story.story?.decorators || []), | ||
...(meta?.decorators || []), | ||
...(globalConfig?.decorators || []), | ||
]; | ||
|
||
const decorated = defaultDecorateStory(finalStoryFn, combinedDecorators); | ||
|
||
return ((extraArgs: Record<string, any>) => | ||
decorated({ | ||
id: '', | ||
kind: '', | ||
name: '', | ||
argTypes: globalConfig.argTypes, | ||
globals: globalConfig.globalTypes, | ||
parameters: combineParameters( | ||
globalConfig.parameters || {}, | ||
meta.parameters || {}, | ||
story.story?.parameters || {}, | ||
story.parameters || {} | ||
), | ||
args: { | ||
...meta.args, | ||
...story.story?.args, | ||
...story.args, | ||
...extraArgs, | ||
}, | ||
})) as Story<Partial<GenericArgs>>; | ||
} | ||
|
||
/** | ||
* Function that will receive a stories import (e.g. `import * as stories from './Button.stories'`) | ||
* and optionally a globalConfig (e.g. `import * from '../.storybook/preview`) | ||
* and will return an object containing all the stories passed, but now as a composed component that has all args/parameters/decorators/etc combined and applied to it. | ||
* | ||
* | ||
* It's very useful for reusing stories in scenarios outside of Storybook like unit testing. | ||
* | ||
* Example: | ||
*```jsx | ||
* import { render } from '@testing-library/react'; | ||
* import { composeStories } from '@storybook/react'; | ||
* import * as stories from './Button.stories'; | ||
* | ||
* const { Primary, Secondary } = composeStories(stories); | ||
* | ||
* test('renders primary button with Hello World', () => { | ||
* const { getByText } = render(<Primary>Hello world</Primary>); | ||
* expect(getByText(/Hello world/i)).not.toBeNull(); | ||
* }); | ||
*``` | ||
* | ||
* @param storiesImport - e.g. (import * as stories from './Button.stories') | ||
* @param [globalConfig] - e.g. (import * as globalConfig from '../.storybook/preview') this can be applied automatically if you use `setGlobalConfig` in your setup files. | ||
*/ | ||
export function composeStories<T extends { default: Meta } & { [K in keyof T]: T[K] }>( | ||
storiesImport: T, | ||
globalConfig?: GlobalConfig | ||
) { | ||
const { default: meta, ...stories } = storiesImport; | ||
|
||
// Compose an object containing all processed stories passed as parameters | ||
return Object.entries(stories).reduce((storiesMap, [key, story]: [string, Story]) => { | ||
// eslint-disable-next-line no-param-reassign | ||
storiesMap[key] = composeStory(story, meta, globalConfig); | ||
return storiesMap; | ||
}, {} as { [key: string]: Story }) as Pick<T, Exclude<keyof T, 'default'>>; | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
```js | ||
// setupFile.js | ||
import { setGlobalConfig } from '@storybook/react'; | ||
import * as globalStorybookConfig from './.storybook/preview'; | ||
|
||
setGlobalConfig(globalStorybookConfig); | ||
``` |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
```js | ||
// Button.test.js | ||
|
||
import React from 'react'; | ||
import { composeStories } from '@storybook/react'; | ||
import { render, screen } from '@testing-library/react'; | ||
import * as stories from './Button.stories'; | ||
import '@testing-library/jest-dom/extend-expect'; | ||
|
||
const { Primary } = composeStories(stories); | ||
|
||
it('renders the button in the primary state with custom text', () => { | ||
render(<Primary>Hello world</Primary>); | ||
expect(screen.getByRole('button')).toHaveTextContent('Hello world'); | ||
}); | ||
``` |
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
14 changes: 11 additions & 3 deletions
14
...s/cra-ts-essentials/.storybook/preview.js → .../cra-ts-essentials/.storybook/preview.tsx
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
import { setGlobalConfig } from '@storybook/react'; | ||
import * as globalStorybookConfig from './.storybook/preview'; | ||
|
||
setGlobalConfig(globalStorybookConfig); |
20 changes: 0 additions & 20 deletions
20
examples/cra-ts-essentials/src/stories/1-Button.stories.tsx
This file was deleted.
Oops, something went wrong.
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import React from 'react'; | ||
import { render } from '@testing-library/react'; | ||
import { composeStories, composeStory } from '@storybook/react'; | ||
|
||
import * as stories from './Button.stories'; | ||
|
||
// example with composeStories, returns an object with all stories composed with args/decorators | ||
const { Primary } = composeStories(stories); | ||
|
||
// example with composeStory, returns a single story composed with args/decorators | ||
const Secondary = composeStory(stories.Secondary, stories.default); | ||
|
||
test('renders primary button', () => { | ||
const { getByText } = render(<Primary>Hello world</Primary>); | ||
const buttonElement = getByText(/Hello world/i); | ||
expect(buttonElement).not.toBeNull(); | ||
}); | ||
|
||
test('reuses args from composed story', () => { | ||
const { getByText } = render(<Secondary />); | ||
const buttonElement = getByText(/Children coming from story args!/i); | ||
expect(buttonElement).not.toBeNull(); | ||
}); | ||
|
||
test('onclick handler is called', async () => { | ||
const onClickSpy = jest.fn(); | ||
const { getByRole } = render(<Secondary onClick={onClickSpy} />); | ||
const buttonElement = getByRole('button'); | ||
buttonElement.click(); | ||
expect(onClickSpy).toHaveBeenCalled(); | ||
}); | ||
|
||
/** | ||
* FIXME: this would only work in typescript projects when composeStories returns type Story<Partial<Props>>. | ||
* It breaks now because Primary contains non-optional props. | ||
* */ | ||
// eslint-disable-next-line jest/no-commented-out-tests | ||
// test('reuses args from composeStories', () => { | ||
// const { getByText } = render(<Primary />); | ||
// const buttonElement = getByText(/foo/i); | ||
// expect(buttonElement).not.toBeNull(); | ||
// }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Was there a reason not to just do this? I'm not sure if it is a big deal to support non-
passArgsFirst
but this is simple enough?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IMHO we shouldn't support legacy CSF on new features. if you want to use it, migrate!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let me know if we should resolve this conversation :D
I'm happy to do either way