Created
August 12, 2020 18:48
-
-
Save HipsterBrown/bcab6ad9efbb54880e0bafa8cd1dc45c to your computer and use it in GitHub Desktop.
withServer - MirageJS Storybook decorator example
This file contains hidden or 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 React from 'react'; | |
import { makeDecorator, StoryContext, StoryGetter } from '@storybook/addons'; | |
import { DataFetchProvider } from '@betterment/js-runtime'; | |
import { makeServer, Response, Server } from '../server.ts'; | |
interface MirageServerProps { | |
fixtures?: unknown; | |
logging?: boolean; | |
errors?: { | |
[endpoint: string]: number | string; | |
}; | |
} | |
class MirageServer extends React.Component<MirageServerProps> { | |
private server: Server; | |
componentDidMount() { | |
this.server = makeServer(); | |
if (this.props.logging) { | |
this.server.logging = true; | |
} | |
if (this.props.fixtures) { | |
this.server.db.loadData(this.props.fixtures); | |
} | |
if (this.props.errors) { | |
Object.keys(this.props.errors).forEach(endpoint => { | |
const value = this.props.errors[endpoint]; | |
this.server.get(endpoint, () => { | |
if (typeof value === 'number') { | |
return new Response(value); | |
} | |
return new Response(200, {}, { errors: value }); | |
}); | |
}); | |
} | |
} | |
componentWillUnmount() { | |
this.server.shutdown(); | |
} | |
render() { | |
return this.props.children; | |
} | |
} | |
export const withServer = makeDecorator({ | |
name: 'withServer', | |
parameterName: 'server', | |
wrapper: (getStory: StoryGetter, context: StoryContext, { parameters }: { parameters: MirageServerProps }) => { | |
return ( | |
<MirageServer {...parameters}> | |
<DataFetchProvider>{getStory(context)}</DataFetchProvider> | |
</MirageServer> | |
); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment