I'm currently experimenting with a TypeScript-Express application that utilizes MongoDB and Mongoose. To perform testing, I have integrated jest and mongo-memory-server into the project. While I have succeeded in testing the insertion of new documents and retrieving existing ones from the database, I am facing difficulty in handling errors when attempting to retrieve a document that does not 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 = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9de9f8eee9ddf0fcf4f1b3fef2f0">[email protected]</a>';
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('attempting to fetch non-registered user', async (): Promise<void> => {
const notRegisteredEmail = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6c5d9dbd3f6dbd7dfda98d5d9db">[email protected]</a>';
expect(await getUserByEmail(notRegisteredEmail)).toThrowError();
}, 100000);
});