Jest unit testing a function throwing error

孤者浪人 提交于 2021-02-11 12:30:06

问题


I was trying to unit test a function in node which throws an error regardless of any condition. Here is my node function definition.

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

As you can see this function always throws an error whenever it has been called. I tried to execute unit testing to this function using jest .toThrow(error?) method. I was not able to unit test the function as expected.

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

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

Test Case #2

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

Test Case #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.

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?


回答1:


You had it right in your third attempt. The only problem is that you are including the done callback in the test definition. This tells the test that it is asynchronous and it expects you to call the done callback once the test has finished.

As your test is not asynchronous, it should suffice with deleting the done callback in the test definition:

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


来源:https://stackoverflow.com/questions/61285655/jest-unit-testing-a-function-throwing-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!