Skip to content

Commit

Permalink
chore(story📗): extract MSW logic into a loader
Browse files Browse the repository at this point in the history
experiment with loaders

the loaders are async and execute before the story is rendered

https://storybook.js.org/docs/react/writing-stories/loaders
https://mswjs.io/

Co-authored-by: Yann Braga <[email protected]>
  • Loading branch information
virtuoushub and yannbf committed May 2, 2022
1 parent 97b49a5 commit bc89956
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 26 deletions.
2 changes: 2 additions & 0 deletions packages/testing/config/storybook/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const { merge } = require('webpack-merge')
// booting up the mock server workers, and mocking the router.
const {
StorybookProvider,
MockingLoader,
} = require('@redwoodjs/testing/dist/web/StorybookProvider')

// Import the user's default CSS file
Expand All @@ -18,6 +19,7 @@ const baseConfig = {
(storyFn, { id }) =>
React.createElement(StorybookProvider, { storyFn, id }),
],
loaders: [MockingLoader],
}

const userConfig = require('~__REDWOOD__USER_STORYBOOK_PREVIEW_CONFIG')
Expand Down
41 changes: 15 additions & 26 deletions packages/testing/src/web/StorybookProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,24 @@ import * as React from 'react'
import { MockProviders } from './MockProviders'
import { setupRequestHandlers, startMSW, mockCurrentUser } from './mockRequests'

export const StorybookProvider: React.FunctionComponent<{
storyFn: () => ReactNode | ReactPortal
id: string
}> = ({ storyFn, id }) => {
const [loading, setLoading] = React.useState(true)

React.useEffect(() => {
const init = async () => {
// Import all the `*.mock.*` files.
const reqs = require.context(
'~__REDWOOD__USER_WEB_SRC',
true,
/.+(mock).(js|ts)$/
)
reqs.keys().forEach((r) => {
reqs(r)
})
export const MockingLoader = async () => {
const reqs = require.context(
'~__REDWOOD__USER_WEB_SRC',
true,
/.+(mock).(js|ts)$/
)
reqs.keys().forEach(reqs)

await startMSW('browsers')
setupRequestHandlers()
setLoading(false)
}
init()
}, [id])
await startMSW('browsers')
setupRequestHandlers()

if (loading) {
return null
}
return {}
}

export const StorybookProvider: React.FunctionComponent<{
storyFn: () => ReactNode | ReactPortal
id: string
}> = ({ storyFn }) => {
// default to a non-existent user at the beginning of each story
mockCurrentUser(null)

Expand Down

0 comments on commit bc89956

Please sign in to comment.