Mocha/Chai无法从函数中捕捉到错误对象



我对测试javascript相当陌生,并尝试进行测试,在测试中捕捉函数抛出的错误。然而,经过多次尝试,我最终在这里询问如何捕获expect中的错误对象。我指的是这个问答。

这是我的代码:

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
};

以下是我在测试文件中所写的内容:

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

在这里,我试图匹配错误的类型以及错误的字符串,但没有通过它

我还尝试了一些类似的代码,

expect(function () {
course;
}).to.throw(Error, 'User must be a volunteer');

问题是,您正在尝试测试异步函数是否抛出错误。异步函数只是在内部转换为promise的普通函数。承诺不会抛出,但它们会拒绝。您必须在异步父函数中使用.catch()catch() {}来处理它们的错误。

在Chai中处理此问题的一种方法是使用Chai as Promise库,该库是Chai的插件,可以处理基于Promise的检查。

以下是应该做什么的示例:

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

相关内容

最新更新