Skip to content

Instantly share code, notes, and snippets.

@gaearon
Last active May 29, 2023 05:23
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaearon/adf9d5500e11a4e7b2c6f7ebf994fe56 to your computer and use it in GitHub Desktop.
Save gaearon/adf9d5500e11a4e7b2c6f7ebf994fe56 to your computer and use it in GitHub Desktop.
'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'
);
});
'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