Skip to content

Instantly share code, notes, and snippets.

@8lane
Created January 22, 2018 11:49
Show Gist options
  • Save 8lane/eb72c7d7504c4ea701ecb87a98aad3f9 to your computer and use it in GitHub Desktop.
Save 8lane/eb72c7d7504c4ea701ecb87a98aad3f9 to your computer and use it in GitHub Desktop.
React 16 componentDidCatch Jest/Enzyme unit test
import React from 'react'
import PropTypes from 'prop-types'
class ErrorBoundary extends React.Component {
constructor (props) {
super(props)
this.state = { hasError: false }
}
componentDidCatch (error, info) {
console.log(error)
this.setState({ hasError: true })
}
render () {
if (this.state.hasError) {
return null
}
return this.props.children
}
}
ErrorBoundary.propTypes = {
children: PropTypes.object
}
export default ErrorBoundary
import React from 'react'
import { shallow } from 'enzyme'
import ErrorBoundary from './ErrorBoundary'
describe('When no JS errors are caught in a child component', () => {
let ErrorBoundaryComponent
beforeAll(() => {
ErrorBoundaryComponent = shallow(<ErrorBoundary><h1>wassup</h1></ErrorBoundary>)
})
it('should render the child component', () => {
expect(ErrorBoundaryComponent.find('h1').exists()).toBeTruthy()
})
})
describe('When a JS error is caught in a child component', () => {
let ErrorBoundaryComponent
beforeAll(() => {
jest.spyOn(global.console, 'log')
ErrorBoundaryComponent = shallow(<ErrorBoundary><h1>wassup</h1></ErrorBoundary>)
ErrorBoundaryComponent.instance().componentDidCatch('oh nooos an error')
ErrorBoundaryComponent.update()
})
it('should log an error to console', () => {
expect(global.console.log).toHaveBeenCalledWith('oh nooos an error')
})
it('should update the state to indicate an error', () => {
expect(ErrorBoundaryComponent.instance().state.hasError).toBeTruthy()
})
it('should not render the child component', () => {
expect(ErrorBoundaryComponent.find('h1').exists()).toBeFalsy()
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment