0

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');
Farrukh Faizy
  • 1,203
  • 2
  • 18
  • 30

1 Answers1

1

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");
gear4
  • 745
  • 6
  • 13
  • Thanks, man :). I haven't thought about it as I already doing await part in the course to resolve it before passing it to expect. However, expect(course).to.eventually.be.rejectedWith("User must be a volunteer"); without await also working fine. – Farrukh Faizy May 09 '21 at 00:00
  • 1
    @farrukh-faizy I do not recommend you omit the `await`, since all async functions *must* be awaited (handled) for them to be considered "valid" in the error handler. I'm glad I could be of help, though :) – gear4 May 09 '21 at 00:01