Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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();
});

enter image description here

Test Case #2

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

enter image description here

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

enter image description here

What is the issue with my implementation? What is the correct method to unit test a function which throws an error object back?

like image 466
Nitheesh Avatar asked Apr 08 '26 15:04

Nitheesh


1 Answers

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();
});
like image 193
mgarcia Avatar answered Apr 11 '26 04:04

mgarcia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!