vendredi 22 novembre 2019

Why jest expects an anonymous function to catch an error?

I have not comprehended what's the reason behind the fact that expects a curried function when I want to test the output of the error message. If it was going to be a return value a direct call to the function leads to the value to be tested correctly in .toBe

function calculateMedian({numbers}) {
if (Array.isArray(numbers) && numbers.length === 0) {
        throw new Error('Cannot calcuate median without any numbers');
    }
}

However, if i were to test the following snipped without the anonymous function the test will simply fail. What is the reason behind it?

Passing Test

    it('should throw an error when given an empty array', () => {
        expect(() =>
            calculateMedian({
                numbers: [],
            }),
        ).toThrow('Cannot calcuate median without any numbers');
    });

Failing Test

    it('should throw an error when given an empty array', () => {
        expect(calculateMedian({numbers: []})
        ).toThrow('Cannot calcuate median without any numbers');
    });

Aucun commentaire:

Enregistrer un commentaire