I am fairly new in testing javascript and try to make a test where I can catch the error thrown by the function and catch it in the test. However, after many tries, I ended up here asking about how should I catch the error object in expect. I was referring to this Q/A.
Here is my code:
export const createCourse = async (courseData: ICourse, userId: string) => {
logInfo('Verifying if user is a volunteer');
const volunteer: Volunteer | null = await getVolunteer(userId);
if (volunteer == null) {
logError('User must be a volunteer');
throw new Error('User must be a volunteer');
}
// do some stuff
};
Here what I am writing in a test file:
describe.only('Try creating courses', function () {
before(async function () {
user_notVolunteer = await addUser(UserNotVolunteer);
});
after(async function () {
await deleteUser(UserNotVolunteer.email);
});
it('Creating a course when user is not volunteer', async function () {
course = await createCourse(test_course, user_notVolunteer.id);
expect(course).to.throws(Error,'User must be a volunteer');
});
});
Here I am trying to match the type of error as well as the string of the Error but not getting passing it.
I also tried few more code like this,
expect(function () {
course;
}).to.throw(Error, 'User must be a volunteer');