Skip to content

Exception in event handler always results in test failureΒ #1068

@stefee

Description

@stefee

I'm finding that when an error is thrown from inside an onClick handler, the test will fail and there's no way for us to assert on the error. I feel like this might be a regression based on this conversation #624 (which seems to be about onClick exceptions not resulting in exceptions).

The behavior I'm seeing (exception from within event handler results in unrecoverable error) means we can essentially never throw exceptions inside event handlers, since this makes it impossible for us to test the error handling of our components. This is problematic because some error tracking SDKs like DataDog RUM will treat unhandled exceptions differently to console.error. If we are forced to catch exceptions inside event handlers and log them, rather than allowing them to become unhandled exceptions, this makes it harder to track errors.

Here's an example:

function MyComponent() {
  function onClick() {
    try {
      ... // do something that might throw
    } catch (err) {
      ... // show error toast in the UI

      throw err; // throw err again because we want this to be an unhandled exception from the browser's point of view
    }
  }

  return (
    <button onClick={onClick}>Click Me</button>
  );
}

In this example, we want to be able to test the "show error toast" part in our unit tests, but we can't since the throw err will result in a test failure regardless.

Is the above considered to be bad practice, and we should be logging instead of throwing inside the catch? Or is this an issue with the test library?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions