简体   繁体   English

开玩笑单元测试 function 抛出错误

[英]Jest unit testing a function throwing error

I was trying to unit test a function in node which throws an error regardless of any condition.我试图在节点中对 function 进行单元测试,无论任何条件,它都会引发错误。 Here is my node function definition.这是我的节点 function 定义。

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

As you can see this function always throws an error whenever it has been called.正如你所看到的,这个 function 总是在被调用时抛出一个错误。 I tried to execute unit testing to this function using jest .toThrow(error?) method.我尝试使用 jest .toThrow(error?)方法对此 function 执行单元测试。 I was not able to unit test the function as expected.我无法按预期对 function 进行单元测试。

The below mentioned are the test cases that I wrote and have attached the screenshot of the errors that I faced while executing the same.下面提到的是我编写的测试用例,并附上了我在执行相同时遇到的错误的屏幕截图。

Test Case #1测试用例 #1

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

在此处输入图像描述

Test Case #2测试用例 #2

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

在此处输入图像描述

Test Case #3测试用例 #3

From this blog, it was mentioned that这个博客,有人提到

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.如果我们希望 function 对某些输入参数抛出异常,关键是我们必须传入 function 定义,而不是在 expect 中调用 ZC1C425268E68385D1AB5074C17A94F。

So I updated my test case as所以我将我的测试用例更新为

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

But it was throwing error like但它抛出了错误,比如

在此处输入图像描述

What is the issue with my implementation?我的实施有什么问题? What is the correct method to unit test a function which throws an error object back?对 function 进行单元测试的正确方法是什么,它会返回错误 object?

You had it right in your third attempt.您在第三次尝试中做对了。 The only problem is that you are including the done callback in the test definition.唯一的问题是您在测试定义中包含了done回调。 This tells the test that it is asynchronous and it expects you to call the done callback once the test has finished.这告诉测试它是异步的,并且它希望您在测试完成后调用done回调。

As your test is not asynchronous, it should suffice with deleting the done callback in the test definition:由于您的测试不是异步的,因此在测试定义中删除done回调就足够了:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM