Using Jest to test a function which should throw an error, but always received "function did not throw" error

Viewed 2154

I was trying to write a unit test for a simple try-catch structure function. My function is in index.js, and the test is in check.test.js. I am not sure what caused this issue.

Inside of index.js:

// index.js

const UNDEFINED_ERROR = "Undefined detected.";
testFn = () => {
    try{ 
       throw new Error(UNDEFINED_ERROR);
    }catch(e){
      console.log(e);
    }
};

module.exports = {
    testFn,
    UNDEFINED_ERROR
}

Inside of check.test.js:

//check.test.js

const {testFn, UNDEFINED_ERROR} = require('./src/index');

describe('test', ()=>{
    it('show throw',()=>{
        expect(()=>{
          testFn();
        }).toThrow();
    });
});

After npm test, the test will fail and the terminal will give back Received function did not throw.

I referenced this similar question, it will perfectly run and pass after deleting try-catch in function, which is just

// passed version

const UNDEFINED_ERROR = "Undefined detected.";

testFn = () => {
    throw new Error(UNDEFINED_ERROR);
};

module.exports = {
    testFn,
    UNDEFINED_ERROR
}

I am a rookie for JS and Jest and I am really appreciate any help here!

2 Answers

If the function doesn't accept arguments, it can be

    expect(testFn).toThrow();

instead of

    expect(() => testFn()).toThrow();

The problem is that testFn isn't supposed to throw an error, the error is always handled.

It should be:

jest.spyOn(console, 'log');
testFn();
expect(console.log).toBeCalledWith(new Error("Undefined detected."));

You don't need to wrap your function call in another method. You were testing that this "wrapper method" was throwing instead of your function itself. Try this:

describe('test', ()=>{
    it('show throw',()=>{
        expect(testFn()).toThrow();
    });
});
Related