Skip to content

Instantly share code, notes, and snippets.

@mdr
Last active July 20, 2018 08:52
Show Gist options
  • Save mdr/36b75c64e601dbbe8a8a962a8c5a2350 to your computer and use it in GitHub Desktop.
Save mdr/36b75c64e601dbbe8a8a962a8c5a2350 to your computer and use it in GitHub Desktop.
import React from 'react'
import { shallow } from 'enzyme'
const flushPromises = () => new Promise(resolve => setImmediate(resolve))
const fetchTheData = jest.fn()
class MyContainerComponent extends React.Component {
state = { error: null }
async componentDidMount() {
try {
await fetchTheData()
} catch (e) {
this.setState({ error: 'There was a problem' })
throw e // rethrow so it gets handled by a generic unhandled promise rejection handler (e.g. Sentry)
}
}
render() {
return <p>{this.state.error}</p>
}
}
it('should handle errors fetching the data', async () => {
fetchTheData.mockImplementation(() => Promise.reject(new Error('something bad happened')))
const component = shallow(<MyContainerComponent />)
await flushPromises()
expect(component.update()).toIncludeText('There was a problem')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment