我试图对节点中的某个函数进行单元测试,无论任何情况,该函数都会引发错误。这是我的节点函数定义。
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
在this博客中,有人提到
如果我们希望某个函数抛出某些异常 输入参数,关键是我们必须传递一个函数 定义而不在期望中调用我们的函数。
所以我将测试用例更新为
it('Should throw test error', (done) => {
const testClass = TestClassService.getInstance();
expect(() => testClass.testFunction()).toThrow();
});
但是它抛出了类似的错误
我的实现有什么问题?单元测试将错误对象扔回去的函数的正确方法是什么?
答案 0 :(得分:1)
您第三次尝试就对了。唯一的问题是您在测试定义中包括了done
回调。这告诉测试它是异步的,并且希望您在测试完成后调用done
回调。
由于您的测试不是异步的,因此只需删除测试定义中的done
回调即可。
it('Should throw test error', () => {
const testClass = TestClassService.getInstance();
expect(() => testClass.testFunction()).toThrow();
});