'React Jest:- node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */);

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.



Solution 1:[1]

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));
  }, []);

Solution 2:[2]

I ran into the similar issue.

This issue may due to one of the object next to response.data is undefined. Add conditions to check its presense.

This fixed my issue

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dhayaleswaran Chellaramu