Home > Software design >  React Jest:- node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */
React Jest:- node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */

Time:02-11

I have below code in react.

useEffect(() => {
        (async () => {
            await httpClient
                .get(`${config.resourceServerUrl}/inventory/`)
                .then((response) => {
                    setSponsor(response.data.sponsor);
                    setAddress(response.data.address);
                    setPhaseOfTrial(response.data.phaseOfTrial);
                })
                .catch((error) => {
                    alert(error);
                });
        })();
    }, []);

this code works successfully. only issue is , it is failing in jest test case.

describe('ListInventory', () => {
    it('should render successfully', () => {
        const { baseElement } = render(<ListInventory />);
        expect(baseElement).toBeTruthy();
    });
});

Below is the error.

node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read properties of undefined (reading 'get')".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

I am already using catch block. what wrong is in the code? could you please help me with the same.

CodePudding user response:

Try handling the promise using a try-catch block, as:

  useEffect(() => {
    (async () => {
      try {
        let response = await httpClient.get(
          `${config.resourceServerUrl}/inventory/`
        );
        setSponsor(response.data.sponsor);
        setAddress(response.data.address);
        setPhaseOfTrial(response.data.phaseOfTrial);
      } catch(error) {
        alert(error);
      }
    })();
  }, []);

or

  useEffect(() => {
    (async () => {
        let response = await httpClient.get(
          `${config.resourceServerUrl}/inventory/`
        );
        setSponsor(response.data.sponsor);
        setAddress(response.data.address);
        setPhaseOfTrial(response.data.phaseOfTrial);
    })().catch(e=>alert(e));
  }, []);
  • Related