我试图对节点中的一个函数进行单元测试,无论任何条件如何,该函数都会引发错误。这是我的节点函数定义。
public testFunction() {
throw new Error('Test Error');
}
正如您所看到的,无论何时调用该函数,它总是会抛出错误。我尝试使用 jest 对此函数执行单元测试.toThrow(错误?) https://jestjs.io/docs/en/expect#tothrowerror方法。我无法按预期对该功能进行单元测试。
下面提到的是我编写的测试用例,并附上了我在执行相同测试时遇到的错误的屏幕截图。
测试用例 #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
From this http://eloquentcode.com/expect-a-function-to-throw-an-exception-in-jest博客中,有人提到
如果我们希望函数在某些情况下抛出异常
输入参数,关键是我们必须传入一个函数
定义而不是在期望中调用我们的函数。
所以我将我的测试用例更新为
it('Should throw test error', (done) => {
const testClass = TestClassService.getInstance();
expect(() => testClass.testFunction()).toThrow();
});
但它抛出了类似的错误
我的实施有什么问题?对抛出错误对象的函数进行单元测试的正确方法是什么?