Greed94
Greed94

Reputation: 178

React tests - UnhandledPromiseRejection

I want to test my application with Jest and Enzyme. I'm getting 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 "[object Object]".] {
  code: 'ERR_UNHANDLED_REJECTION'
}

It is caused by:

async function checkGet() {
    const fetchedDB = await db.persons.toArray();
    if (fetchedDB.length > 0) {
      setPeople(fetchedDB);
      return;
    } else {
      getPeople();
    }
  }

I tried to change it like that:

 async function checkGet() {
    const fetchedDB = await db.persons.toArray();
    fetchedDB.catch((e) => {
      console.log(e);
    });
    if (fetchedDB.length > 0) {
      setPeople(fetchedDB);
      return;
    } else {
      getPeople();
    }
  }

And like that:

  async function checkGet() {
    const fetchedDB = await db.persons.toArray().catch((e) => {
      console.log(e);
    });
    if (fetchedDB.length > 0) {
      setPeople(fetchedDB);
      return;
    } else {
      getPeople();
    }
  }

But even after adding this, error still exists. I'm using React 17. Is it some sort of bug?

Upvotes: 4

Views: 27807

Answers (1)

Ariel
Ariel

Reputation: 1436

Try wrapping your code with try/catch.

async function checkGet() {
  try {
    const fetchedDB = await db.persons.toArray();
    if (fetchedDB.length > 0) {
      setPeople(fetchedDB);
      return;
    } else {
      getPeople();
    }
  } catch (err) {
     console.log(err);
  }
}

All errors thrown inside try{} will be grabbed in catch(err){}.

Upvotes: 4

Related Questions