-
-
Save gaearon/adf9d5500e11a4e7b2c6f7ebf994fe56 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
'use strict'; | |
const React = require('react'); | |
const ReactDOM = require('react-dom'); | |
const { expectRenderError } = require('./expectRenderError'); | |
function Darth() { | |
throw new Error('I am your father') | |
} | |
it('errors', () => { | |
expectRenderError( | |
<Darth />, | |
'father' | |
); | |
}); |
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
'use strict' | |
// Note: feel free to put this helper on npm or something. | |
// It would probably make a nice Jest matcher? | |
// e.g. expect(<Child />).toThrowRendering('...') | |
// Feel free to tweak it to your needs! | |
const React = require('react'); | |
const ReactDOM = require('react-dom'); | |
function expectRenderError(element, expectedError) { | |
// Noop error boundary for testing. | |
class TestBoundary extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { didError: false }; | |
} | |
componentDidCatch(err) { | |
this.setState({ didError: true }); | |
} | |
render() { | |
return this.state.didError ? null : this.props.children; | |
} | |
} | |
// Record all errors. | |
let topLevelErrors = []; | |
function handleTopLevelError(event) { | |
topLevelErrors.push(event.error); | |
// Prevent logging | |
event.preventDefault(); | |
} | |
const div = document.createElement('div'); | |
window.addEventListener('error', handleTopLevelError); | |
try { | |
ReactDOM.render( | |
<TestBoundary> | |
{element} | |
</TestBoundary>, | |
div | |
); | |
} finally { | |
window.removeEventListener('error', handleTopLevelError); | |
} | |
expect(topLevelErrors.length).toBe(1); | |
expect(topLevelErrors[0].message).toContain(expectedError); | |
} | |
module.exports = { expectRenderError }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment