-
-
Save imdongchen/cb3901a8f9ea865c0caf17459d82d446 to your computer and use it in GitHub Desktop.
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
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