score:2
The problem is indeed React's error handling prevents the error from bubbling up to the top-level, where Jasmine can detect it. Two possible workarounds:
Monkeypatch console.error to actually throw
console.error = msg => { throw new Error(msg); };
This is obviously hack and would break if React changed to use a different approach for error reporting. stijndepestel's answer is a more robust approach to this.
Create an error boundary just for testing
let errorInfo = null;
class ErrorBoundary extends React.PureComponent {
state = {hasError: false};
componentDidCatch(err, info) {
errorInfo = [err, info]
this.setState({hasError: true});
}
render() {
if (!this.state.hasError)
return React.Children.only(this.props.children);
return 'Errored';
}
}
You can then wrap your test in a handler like this one and then assert that errorInfo
is not null and that it contains an error as you expect
score:6
I have had a similar problem with the virtual-console from jsdom printing the error instead of throwing it. As far as I know, there is no way for Jest or any other testing framework to prevent code from printing to the console.
I have fixed this by replacing the listener that is responsible for printing to the console. The following code is run in a file which is configured in the setupFiles
in the Jest configuration.
// There should be a single listener which simply prints to the
// console. We will wrap that listener in our own listener.
const listeners = window._virtualConsole.listeners("jsdomError");
const originalListener = listeners && listeners[0];
window._virtualConsole.removeAllListeners("jsdomError");
window._virtualConsole.addListener("jsdomError", (error) => {
if (error.type !== "not implemented" && originalListener) {
originalListener(error);
}
// swallow
});
As you can see, in our case the error that was printed to the console (multiple times, as it was a side effect, and not the main purpose of our test) was a 'not-implemented' error. So it is only those kinds of errors that this code will swallow.
This solution is not ideal, but it will keep the logs cleaner.
PS: If you want to reduce the risk of swallowing 'real' errors, you might be able to use this trick in the before
method of your test suite and use the after
method to reset the original behaviour.
Source: stackoverflow.com
Related Query
- Jest test passes but error not caught and logs to console
- Jest test passes but .. has console message You are trying to access a property or method of the Jest environment after it has been torn down
- includes() and toLowerCase throws not a function error from jest unit test
- Material-UI Dialog Reusable Component Not Working but no error in the console and app does not crash
- WebRTC getting Failed to execute 'addIceCandidate' on RTCPeerConnection error on console but can still display remote and local videos
- Unable to test post methods with Jest due to error can not read mockImplementation of undefined
- Why does chrome dev tools console show a link for Post 500 error in one website but not another?
- ReferenceError: window is not defined. I got this error when I run npm test to unit testing by jest
- "Type Error : is not a function" in a Jest test
- Why in React, my axios API call has Authorization Header which contains Bearer <token> but not being authorized and gives 401 error
- Jest test (ReferenceError: google is not defined) ReactJS and Google Charts
- react - writting twice same test passes first but not second time
- Jest test passes locally but fails in azure devops
- How to test if a component is rendered or not by jest and enzyme?
- Trying to integrate jest and react with amchart but getting an error . What could be the issue?
- Build library and include CSS files but not test files
- Why is my state showing up in my console logs but not my HTML?
- Jest did not exit one second after the test run has completed when using GitHub Actions and Firebase
- React test passes but component does not work properly when state updated in document.addListener handler
- Jest testing onClick() gets error 'Expected mock function to have been called, but it was not called.'
- react router not working and no erros in console or compilation error is shown [ react router dom v5]
- Kubernetes and Socket.io 404 error - works locally but not after applying to kubernetes
- Jest test does not fail on error while rendering
- How to Test React's Error Boundary using Jest and React Testing Library
- Typescript error on local machine but not on remote test server
- Jest Enzyme test error :Could not find "store" in the context of "Connect(App)"
- Cors issue i also set the proxy in pkg.json due to cors and set the api according to it but this error is not remove
- I am trying to start a new react project But I am getting this error and the app is not created. I have installed react globally
- jest enzyme test method in componentDidMount fails but console shows that it is working
- Why my state is not getting set inside class based component and it should work but it is not neither i am getting error
More Query from same tag
- React/Redux - Why this Promise.all continues to execute after dispatch?
- ReactJs - Initialize Redux Store from URL query parameters
- React - How to apply gradient with browsers-prefixs on a props value?
- React hooks. Why doesn't set function change state?
- firebaseApp is not defined in firebase file
- User authentication with Axios using React-Redux
- Pass state from one component to another stateless component
- "Cannot read property 'then' of undefined" when dispatching action
- React checkbox toggle: behaviour is opposite to that expected
- Since updating react-dom and react-router-dom packages: behaviors executing additional times
- Mocking Submit of final-form in react
- Spring webflux data in ReactJs UI
- Adding validation to simple React + Typescript application
- Why does Khan Academy use templates with just empty space?
- How can I access the data inside this function? I believe it is a promise, but I'm not sure
- 'Active' styling not being applied in conditional statement in React
- How to invoke a function written in html root script from a react component
- passing image from list(stateless) component to display(stateful) component --react
- How does this useState hook work in React?
- React: Visually reset HTML select tag from onClick in sibling component
- why toUpperCase not working in nextjs while adding slug
- React - Cannot get property setState of null
- React Victory Chart: VictoryTooltip is not working
- How to relaunch MongoDB Compass on windows machine
- When to use plain state over constructor(props)?
- React.js tests TypeError: Cannot read property 'pushState' of undefined
- ReactJS - Showing some elements and a button to show more
- Reactjs Add dynamic component into other component
- How do you apply a style to icon of type IIconProps in Fluid UI?
- npm ERR! code ERESOLVE unable to resolve dependency tree