开玩笑期望不会从异步等待功能中抛出错误

时间:2019-04-27 06:17:45

标签: typescript express jestjs integration-testing supertest

我正在用MongoDB和Mongoose测试Typescript-express ap。对于此测试,我正在使用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);
});

3 个答案:

答案 0 :(得分:0)

我以前遇到过这个问题,我发现传递匿名函数可以使它起作用:

foreach (var rule in filter.ToRuleGroup().Rules)
{
    entity = entity.Where(Rule.Any((Product p) => p.Attributes.Select(a => a.Attribute), rule));
}

答案 1 :(得分:0)

我在这里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);

答案 2 :(得分:0)

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

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