【问题标题】:Jest expect doesn't catch throw from async await function开玩笑的期望不会从异步等待函数中捕获抛出
【发布时间】:2021-02-04 23:54:12
【问题描述】:

我正在使用 MongoDB 和 Mongoose 测试 typescript-express 应用程序。对于这个测试,我使用的是 jest 和 mongo-memory-server。 我能够测试插入新文档并将现有文档检索到数据库中,但是当我无法捕获错误时 文档不存在。

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 = 'test@mail.com';
  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 = 'some@mail.com';
    expect(await getUserByEmail(notRegisteredEmail)).toThrowError();
  }, 100000);
});

【问题讨论】:

    标签: typescript express jestjs integration-testing supertest


    【解决方案1】:

    遇到同样的问题后,这对我有用:

    await expect(asyncFuncWithError()).rejects.toThrow(Error)
    

    【讨论】:

      【解决方案2】:

      我之前遇到过这个问题,我发现传入一个匿名函数可以让它工作:

      const throwFn = () => { throw new Error() };
      
      // won't work
      it('should throw', () => {
        expect(throwFn()).toThrow();
      });
      
      // works ¯\_(ツ)_/¯
      it('should throw', () => {
        expect(() => throwFn()).toThrow();
      });
      

      【讨论】:

      • 在我的情况下它不起作用,我认为这是因为它是异步等待功能
      【解决方案3】:

      我在这里找到了解决方案jest issues on github

      it('fetching non registered user', async (): Promise<void> => {
          const nonRegisteredEmail = 'nonREgisteredEmail.com';
          await expect(getUserByEmail(nonRegisteredEmail)).rejects.toThrow(
            new Error('Error: Validation Error'),
          );
        }, 100000);

      【讨论】:

        猜你喜欢
        • 2023-02-08
        • 1970-01-01
        • 2018-06-11
        • 1970-01-01
        • 2021-05-06
        • 2020-03-11
        • 1970-01-01
        • 1970-01-01
        • 2020-10-01
        相关资源
        最近更新 更多