Promise test case failing only for Node 16

Viewed 100

We are currently upgrading from Node v12 to Node v16.

After the node version update, the following test is failing with this error.

[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 "Error".] { code: 'ERR_UNHANDLED_REJECTION'

But why does a node version cause this.

This error stops if I remove the .catch() from the test case.
But it is still incorrect outcome cos the snapshot no longer matches if I do that.

This is the test.

it('should test', async () => {
  const thePromise = Promise.resolve({
    json: () => {
      Promise.reject(new Error());
    },
  });

  // validateData is fetch call. 
  validateData.mockReturnValueOnce(thePromise);

  const rendered = renderModule({ state: { code: 'mockRefCode' } });
  rendered.find('#btn').simulate('click');
  await ((thePromise)).then().catch(); // If i remove this catch, above error gone but wrong snapshot (null snapshot).
  expect(rendered.find('#error')).toMatchSnapshot();
});

This is the code being tested.

export const validateCode = async (env, code) => fetch(`www.getapiresponse.example`);

export const SomeReactComponent(props) {
  …
  const [validatingCode, setValidatingCode] = useState(false);
  const [validationError, setValidationError] = useState('');

  const validateData = () => {
    if (!code) {
      setValidationError(langPack.emptyField);
      return;
    }

    setValidatingCode(true);
    validateCode(environment, code.trim())
      .then((response) => response.json())
      .then((body) => {
        if (body.response_status_code !== '200') {
          // some logging
        } else {
          setValidationError('');
        }
      })
      .catch(() => setValidationError(langPack.serviceError))
      .finally(() => setValidatingCode(false));
  };
    
  …
}

If I remove the .catch(), the snapshot ends up as null.

The correct snapshot should be something like following:

- <div
-   className="error"
-   id="error"
- >
-   service
- </div>
0 Answers
Related