Farrukh Faizy
Farrukh Faizy

Reputation: 1235

Mocha/Chai unable to catch error object from a function

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');

Upvotes: 0

Views: 933

Answers (1)

gear4
gear4

Reputation: 844

The problem is that, you're trying to test if an async function throws an error. Async functions are just normal functions which, internally, convert into promises. Promises do not throw, but they do reject. You have to handle their errors using .catch() or catch() {} in an async parent function.

A way to handle this in Chai is to use the chai-as-promised library, which is a plugin to Chai and enables handling of Promise-based checks.

Here is an example of what you should be doing:

const course = createCourse(test_course, user_notVolunteer.id);
await expect(course).to.eventually.be.rejectedWith("User must be a volunteer");

Upvotes: 1

Related Questions