Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Testing that function returns an Error with jest

I have this function

const filterByTerm = (inputArr, searchTerm) => {
    if(!searchTerm) throw new Error('Search term can not be empty');
    if(!inputArr.length) throw new Error('Input array term can not be empty');

    return inputArr.filter((el) => el.url.match(searchTerm.toLowerCase()))
}

and this is a test where I’m trying to test scnario when the searchTerm is empty. I want to test if there is an Error when it’s happening

describe('Filter function', () => {

    it('Should filter by a search term (link)', () => {
        const input = [
            { id: 1, url: 'https://www.url1.dev' },
            { id: 2, url: 'https://www.url2.dev' },
            { id: 3, url: 'https://www.link3.dev' },
        ];

        const output = [{ id: 3, url: 'https://www.link3.dev' }];
        const output2 = [
            { id: 1, url: 'https://www.url1.dev' },
            { id: 2, url: 'https://www.url2.dev' }
        ]

        expect(filterByTerm(input, '')).toThrow();
        expect(filterByTerm(input, '')).toThrow(Error);
        expect(filterByTerm(input, '')).toThrow('Search term can not be empty');
    });
});

But none of the approaches I saw in Jest documentation is not working.
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Documentation states You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail. Additionally you can combine the second and third tests by using toThrowError.

So you should change your code logic syntax to the following:

expect(() => {filterByTerm(input, '')}).toThrow();
expect(() => {filterByTerm(input, '')}).toThrowError(new Error('Search term can not be empty'));

Link to Documentation here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading