我正在使用 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', (): …Run Code Online (Sandbox Code Playgroud)