Home > Back-end >  Testing that function returns an Error with jest
Testing that function returns an Error with jest

Time:04-10

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

CodePudding user response:

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

  • Related