Skip to content

Instantly share code, notes, and snippets.

@imdongchen
Created April 29, 2021 15:41
Show Gist options
  • Save imdongchen/cb3901a8f9ea865c0caf17459d82d446 to your computer and use it in GitHub Desktop.
Save imdongchen/cb3901a8f9ea865c0caf17459d82d446 to your computer and use it in GitHub Desktop.
let server
/**
* Try importing the browser worker first (msw setupWorker).
* msw would throw an error if it's nodejs environment (e.g. unit test)
* Then use server integration (msw setupServer)
*/
try {
server = require('./worker').worker
} catch {
server = require('./server').server
}
/**
* Use it like
* <ApiMock mocks={[{
* url: '/',
* method: 'get',
* response: mockedResponse,
* }]}>
* <MyComponent {...props} />
* </ApiMock>
*/
export class ApiMock extends Component {
constructor(props: TProps) {
super(props)
this.mock()
}
componentWillUnmount() {
this.unmock()
}
render() {
return this.props.children
}
mock() {
const { mocks } = this.props
server.use(
...mocks.map(({ url, method, response }) => {
return rest[method ?? 'get'](url, (req, res, ctx) => {
if (typeof response === 'function') {
return response(req, res, ctx)
}
return res(ctx.json(response))
})
})
)
}
unmock() {
// remove runtime handlers so that this component will not interfere others
server.resetHandlers()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment