首页 > 解决方案 > Jest 单元测试函数抛出错误

问题描述

我试图对节点中的一个函数进行单元测试,该函数在任何条件下都会引发错误。这是我的节点函数定义。

public testFunction() {
    throw new Error('Test Error');
}

正如你所看到的,这个函数在被调用时总是抛出一个错误。我尝试使用 jest .toThrow(error?)方法对此函数执行单元测试。我无法按预期对功能进行单元测试。

下面提到的是我编写的测试用例,并附上了我在执行相同时遇到的错误的屏幕截图。

测试用例 #1

it('Should throw test error', (done) => {
    const testClass = TestClassService.getInstance();
    expect(testClass.testFunction()).toThrow();
});

在此处输入图像描述

测试用例 #2

it('Should throw test error', (done) => {
    const testClass = TestClassService.getInstance();
    expect(testClass.testFunction).toThrow();
});

在此处输入图像描述

测试用例 #3

这个博客中,有人提到

如果我们希望函数对某些输入参数抛出异常,关键是我们必须传入一个函数定义,而不是在期望中调用我们的函数。

所以我将我的测试用例更新为

it('Should throw test error', (done) => {
    const testClass = TestClassService.getInstance();
    expect(() => testClass.testFunction()).toThrow();
});

但它抛出了错误,比如

在此处输入图像描述

我的实施有什么问题?对抛出错误对象的函数进行单元测试的正确方法是什么?

标签: javascriptnode.jsunit-testingjestjs

解决方案


您在第三次尝试中做对了。唯一的问题是您done在测试定义中包含回调。这告诉测试它是异步的,并且它希望您done在测试完成后调用回调。

由于您的测试不是异步的,因此删除done测试定义中的回调就足够了:

it('Should throw test error', () => {
    const testClass = TestClassService.getInstance();
    expect(() => testClass.testFunction()).toThrow();
});

推荐阅读