react-testing-library icon indicating copy to clipboard operation
react-testing-library copied to clipboard

Errors thrown in event handlers are not propagating to tests

Open armingjazi opened this issue 6 years ago • 5 comments

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.

Reproduction repro

armingjazi avatar Mar 27 '20 16:03 armingjazi

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 avatar Mar 27 '20 16:03 eps1lon

@eps1lon did you manage to find a solution in how to test this?

charklewis avatar Apr 25 '21 12:04 charklewis

@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.

eps1lon avatar Apr 25 '21 12:04 eps1lon

@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)

armingjazi avatar Apr 25 '21 16:04 armingjazi

Ah ok no worries, makes sense. I have done the same! Thanks for the prompt reply.

charklewis avatar Apr 26 '21 04:04 charklewis