Skip to content

Instantly share code, notes, and snippets.

@imdongchen
Created April 29, 2021 15:41
Show Gist options
  • Save imdongchen/d8ad64538428a1d398966e2e7154de51 to your computer and use it in GitHub Desktop.
Save imdongchen/d8ad64538428a1d398966e2e7154de51 to your computer and use it in GitHub Desktop.
import request from 'superagent'
import superagentMock from 'superagent-mock'
export class ApiMock extends Component {
constructor(props) {
super(props)
this.mock()
}
componentWillUnmount() {
this.unmock()
}
render() {
return this.props.children
}
mock() {
const { mocks } = this.props
const mocksConfig = mocks.map(m => ({
pattern: m.url,
fixtures: (match, params, headers, context) => {
if (typeof m.response === 'function') {
return m.response(match, params, headers, context)
}
return m.response
},
[m.method ?? 'get']: (_, data) => data,
}))
// check superagent-mock for their api
this.smock = superagentMock(request, mocksConfig)
}
unmock() {
this.smock.unset()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment