简体   繁体   中英

How can I force a mongodb error to test with jest the try and catch condition

I need to test a code but given the condition that my code is structured i can't make an error occurred and go to the catch condition.

That does not occur because my throw condition for the Promise. All is in another file that handles the returning of the promise

export const userExists = async (name, phone) => {
  try {
    const userExists = await Promise.all([User.findOne({ name}), User.findOne({ phone})]);
    if (userExists.some(el => !!el)) return true;
    else return false;
  } catch (error) {
    return error;
  }
};

Inside of your try block add:

throw new Error("Test Error")

Like so:

export const userExists = async (name, phone) => {
  try {
    throw new Error("Test Error");
    const userExists = await Promise.all([User.findOne({ name}), User.findOne({ phone})]);
    if (userExists.some(el => !!el)) return true;
    else return false;
  } catch (error) {
    return error;
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM