Experimenting with error boundaries by utilizing the React Testing Library and Jest:

I am facing an issue while writing a test for my error boundary higher-order component (HOC). The problem arises when I mock throwing an error in my wrapped component, causing the test to fail because it recognizes the error as a genuine one instead of understanding that it was intended for testing purposes. I'm unsure about what I might be doing incorrectly here.

Here is the code snippet for the ErrorBoundary HOC:


interface StateProps {
  error: unknown;
  info: unknown;
}

interface ErrorBoundaryProps {
  createNotification(...args: any): void;
}

const connector = connect(null, {
  createNotification: createNotificationAction,
});

export const withErrorBoundary = <P extends object>(TargetComponent: React.ComponentType<P>) => {
  class ErrorBoundary extends React.Component<ErrorBoundaryProps, StateProps> {
    constructor(props: ErrorBoundaryProps) {
      super(props);
      this.state = {
        error: null,
        info: null,
      };
    }

    public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
      this.props.createNotification({
        alertType: 'error',
        message: `${TargetComponent.name} is not being rendered. Error: ${error.message}`,
      });
      this.setState({ error, info: errorInfo });
    }

    public render() {
   
      const { ...props } = this.props;
      if (this.state.error instanceof Error) {
        return null;
      }
      return <TargetComponent {...(props as P)} />;
    }
  }

  return connector(ErrorBoundary) as any;
};

And here is the test scenario:


describe('ErrorBoundary HOC', () => {
  let store;
  let createNotification;
  let props;

  beforeEach(() => {
    store = configureStore(defaultState);
    createNotification = jest.fn();

    props = {
      createNotification,
    };

  });

  test('Renders nothing if error', async () => {
    const targetComponent = () => {
      throw new Error('Errored!');
    };
    const WrappedComponent = withErrorBoundary(targetComponent);
    const RenderedComponent = render(
      <BrowserRouter>
        <Provider store={store}>
          <WrappedComponent {...props} />
        </Provider>
      </BrowserRouter>
    );

    await waitFor(() => expect(() => WrappedComponent.toThrow()));
    expect(RenderedComponent.container.hasChildNodes()).toBeFalsy();
    await waitFor(() => expect(createNotification).toHaveBeenCalled());

 
  });

});

Upon investigation, I discovered that the error is thrown before rendering in the test environment. However, I am still uncertain about how to resolve this issue.

Thank you in advance for any assistance provided.

Answer №1

Before a functional component renders, all code before the return statement is executed except for any logic inside the useEffect() hook.

Even if the targetComponent function does not return any JSX to render, it still executes within the component.

If you want to throw an error after rendering, you can do so like this:

const targetComponent = () => {
  useEffect(() => {
    throw new Error('Error occurred!');
  }, [])
}

This may not fulfill your testing requirements completely, but it can serve as a starting point.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Triggering an event from a higher-level component to a lower-level component

Within the parent component named personDetails, there is a Submit button. This parent component contains multiple child components called person`. Each time I click on the Submit button, I need to trigger a method within the child component. Is it possib ...

Exploring an Angular Real-World Example Application on Github - Resolving the Following Bug

my surroundings. export const environment = { production: false, api_url: 'localhost:3306/api' }; my personal server is at localhost:3306 (MAMP) The instructions provided are to edit src/environments/environment.ts in order to ch ...

Syntax highlighting in VSCode does not seem to be functional when the ?? nullish coalescing operator is being utilized

Hello there! I've recently started using react.js with typescript on a new computer, but I've encountered an issue with syntax highlighting in VSCode. It seems that the problem arises when there's a double question mark (??) in the code, spe ...

Node module for Nativescript angular project that enables multi select dropdown or picker functionality

Does anyone know of a Node NPM module for creating a multi-select dropdown in NativeScript Angular? I've searched through many plugins in the NativeScript marketplace, but haven't been able to find one that fits my needs. I need the plugin to wo ...

Turn off the touch events system for Ionic 2 on the leaflet map's draw controller

Seeking guidance on how to disable data-tap functionality in Ionic 2 within a leaflet map div. Anyone familiar with this? In Ionic-v1, the solution involved adding data-tap-disabled="true" to the map container (ion-content). I recently integrated the lea ...

Just change "this.array[0]..." in the TypeScript code

There is a problem, this.myList[0], this.myList[1], this.myList[2], this.myList[3], // mylist data is 0 ~ 18... this.myList[18] I attempted to solve it by doing the following: for (let i = 0; i < this.myList.length; i++) { this.myList.push( ...

The minimum and maximum validation functions are triggered when I am not utilizing array controls, but they do not seem to work when I use array controls

Take a look at the stack blitz example where min and max validation is triggered: https://stackblitz.com/edit/angular-mat-form-field-icrmfw However, in the following stack blitz with an array of the same controls, the validation does not seem to be worki ...

Exploring the options variables within CLI commander Js action

As a newcomer to developing CLI apps, I've chosen to work with ts-node and commander. However, I'm currently facing a challenge in understanding how to access the options that users pass into my command action. program .version(version) .nam ...

Utilizing Next.js and React to interact with Open AI through API requests

I'm currently experimenting with the OpenAI API to develop a chatbot using React, TypeScript, and Next.js. I am facing an issue where clicking the send button in the UI does not trigger any action. Even after adding console.log statements, nothing sho ...

Testing the functionality of a condition function using Jest can sometimes lead to errors, such as the following: "Matcher error: the received value must be

I recently started learning how to write unit tests with Jest, and I decided to test whether the modal opens after submitting a form. However, I encountered an error: Matcher error: received value must be a mock or spy function. TS buildform(){ this. ...

Retrieve information from a URL to transmit to a different page in NextJS using Typescript and AppRouter

I'm struggling with transitioning from the Home page to the Detail page. I've successfully passed data to the URL from the Home screen, but I'm having trouble accessing it in the Detail screen. I'm working with NextJS ver 13, using Type ...

Transform Sass modules into css during the creation of a component library

I'm in the process of developing a React TypeScript component library that will be utilized in various projects. Currently, I have been using the following script to build this project. "build": "rimraf dist && NODE_ENV=product ...

How is it possible that TypeScript does not provide a warning when a function is called with a different number of arguments than what is expected?

I am working on a vanilla JavaScript project in VS Code and have set up jsconfig.json. Here is an example of the code I am using: /** * @param {(arg: string) => void} nestedFunction */ function myFunction(nestedFunction) { // Some logic here } myFu ...

Ways to invoke a slice reducer from a library rather than a React component

I've been working on a React application using the React Boilerplate CRA Template as my foundation. This boilerplate utilizes Redux with slices, which is great for updating state within a React component. However, I'm facing a challenge when try ...

challenges with template inheritance: when one template takes precedence over another

I have encountered an issue with my two HTML templates, login.html and signup.html. Both of these files inherit from the base.html file, but there seems to be a problem where one file is overriding the title and content of the other. So when I visit /login ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...

What is the implementation of booleans within the Promise.all() function?

I am looking to implement a functionality like the following: statusReady: boolean = false; jobsReady: boolean = false; ready() { return Promise.all([statusReady, jobsReady]); } ...with the goal of being able to do this later on: this.ready().then(() ...

Managing the state of dynamically generated tabs within a NextJS application

Looking to develop a web app in Next.js that includes tabs components. The goal is to manage various entities within each tab, such as utilizing a search bar to select different products. Upon selecting a product, a new tab will be generated with the produ ...

There was an unhandled exception that occurred due to a missing file or directory with the lstat error on 'D:a1s ode_modulesquill'

ngx-quill is causing issues in production, any suggestions? I am currently using "ngx-quill": "^13.4.0", but it is unable to find Quill on my server even though it works locally. The problem persists in the pipeline... An unhandled exception has occurred ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...