typescript - Jest expect no captura el lanzamiento de una función async await
Estoy probando una aplicación de typescript-express con MongoDB y Mongoose. Para esta prueba, estoy usando jest y mongo-memory-server. Puedo probar la inserción de nuevos documentos y la recuperación de los existentes en la base de datos, pero no puedo capturar errores cuando el documento no existe.
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 ';
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 ';
expect(await getUserByEmail(notRegisteredEmail)).toThrowError();
}, 100000);
});
Respuesta #1
Esto funciona para mí, después de encontrar el mismo problema:
await expect(asyncFuncWithError()).rejects.toThrow(Error)
Respuesta #2
Encontré la solución aquí en los problemas de Jest en 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);