Errors thrown in event handlers are not propagating to tests
Hey folks,
I'm not sure if this is an issue for this library, react or even jest-dom, so I'm starting here so where it leads:
for the following component
const ClickThrowsComponent = () => {
const handleOnSectionClick = () => {
throw new Error('some error')
};
return (
<div data-testid='some-id'
onClick={handleOnSectionClick}
/>
);
};
the following test does not pass
test('should throw', () => {
const { getByTestId } = render(<ClickThrowsComponent />);
expect(()=>fireEvent.click(getByTestId('some-id'))).toThrow();
});
somehow the error is being swallowed on the way, I have tried almost all combinations with wrapping in act with async/awaits and promises to no avail
any help would be appreciated.
Thanks for the detailed report.
This is unfortunately not possible since it's inherent to how it works in the DOM.
dispatching an event never throws if a function that handled that error throws. In other terms
Exceptions thrown by event handlers are reported as uncaught exceptions; the event handlers run on a nested callstack: they block the caller until they complete, but exceptions do not propagate to the caller.
-- https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
but exceptions do not propagate to the caller
This bit being the important part.
Maybe you can find a solution to your underlying problem on StackOverflow.
@eps1lon did you manage to find a solution in how to test this?
@eps1lon did you manage to find a solution in how to test this?
@charklewis I didn't look for one. You probably want to ask the author of the issue instead.
@charklewis my solution was not to throw at all. As standard suggests the error is not propagated to the caller, which means the exception should be caught in the callback handler and be dealt with there directly (e.g. with window alert if the message is client relevant)
Ah ok no worries, makes sense. I have done the same! Thanks for the prompt reply.