Languages
[Edit]
EN

JavaScript - catch exception in Jest test

6 points
Created by:
Anisha-Kidd
562

In this short article, we would like to show how to catch expected exception writing tests in Jest in JavaScript.

Quick solution:

test('test name here ...', () => {
    expect(() => doSomeLogic()).toThrow();
});

 

Practical example

import doSomeLogic from './doSomeLogic';

describe('Some logic', () => {
    test('throws always exception', () => {
        expect(() => doSomeLogic()).toThrow();
    });
});

Example output:

Catching exception in Jest test in JavaScript.

Example doSomeLogic.js file:

const doSomeLogic = () => {
    throw new Error('Some exception message here ...');
};

export default doSomeLogic;

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join