我试图对 Node 中的一个函数进行单元测试,无论任何条件,该函数都会抛出错误。这是我的 Node 函数定义。
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博客中,有人提到
If we want to expect a function to throw an exception for certain input parameters, the key point is that we must pass in a function definition and not call our function inside the expect.
所以我将测试用例更新为
it('Should throw test error', (done) => {
const testClass = TestClassService.getInstance();
expect(() => testClass.testFunction()).toThrow();
});
但它抛出了类似的错误
我的实现存在什么问题?对抛出错误对象的函数进行单元测试的正确方法是什么?
最佳答案
你的第三次尝试是正确的。唯一的问题是您在测试定义中包含了 done
回调。这告诉测试它是异步的,并且希望您在测试完成后调用 done
回调。
由于您的测试不是异步的,因此删除测试定义中的 done
回调就足够了:
it('Should throw test error', () => {
const testClass = TestClassService.getInstance();
expect(() => testClass.testFunction()).toThrow();
});
关于javascript - Jest 单元测试函数抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61285655/