Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest expect doesn't catch throw from async await function

I'm testing a typescript-express ap with MongoDB and Mongoose. For this test, I'm using jest and mongo-memory-server. I'm able to test inserting new documents and retrieving existing ones into the database, but I can't catch errors when the document doesn't exist.

const getUserByEmail = async (email: string): Promise<UserType> => {
  try {
    const user = await User.findOne({ email });
    if (!user) {
      const validationErrorObj: ValidationErrorType = {
        location: 'body',
        param: 'email',
        msg: 'User with this email does not exist!',
        value: email,
      };
      const validationError = new ValidationError('Validation Error', 403, [
        validationErrorObj,
      ]);
      throw validationError;
    }
    return user;
  } catch (err) {
    throw new Error(err);
  }
};


let mongoServer: any;
describe('getUserByEmail', (): void => {
  let mongoServer: any;
  const opts = {}; // remove this option if you use mongoose 5 and above
  const email = '[email protected]';
  const password = 'testPassword';
  const username = 'testUsername';

  beforeAll(async () => {
    mongoServer = new MongoMemoryServer();
    const mongoUri = await mongoServer.getConnectionString();
    await mongoose.connect(mongoUri, opts, err => {
      if (err) console.error(err);
    });
    const user = new User({
      email,
      password,
      username,
    });
    await user.save();
  });

  afterAll(async () => {
    mongoose.disconnect();
    await mongoServer.stop();
  });

  it('fetching registered user', async (): Promise<void> => {
    const user = await getUserByEmail(email);
    expect(user).toBeTruthy();
    expect(user.email).toMatch(email);
    expect(user.password).toMatch(password);
    expect(user.username).toMatch(username);
  }, 100000);
  it('fetching non registered user', async (): Promise<void> => {
    const notRegisteredEmail = '[email protected]';
    expect(await getUserByEmail(notRegisteredEmail)).toThrowError();
  }, 100000);
});
like image 215
Ktr1000 Avatar asked Mar 04 '23 02:03

Ktr1000


1 Answers

This works for me, after encountering the same issue:

await expect(asyncFuncWithError()).rejects.toThrow(Error)
like image 103
Seba Illingworth Avatar answered Mar 31 '23 13:03

Seba Illingworth