Norbert
Norbert

Reputation: 2771

Testing function parameter data types in Jest

I have the following function:

export const getRotation = (elementId, position) => {
    if (typeof elementId !== 'string') {
        throw new TypeError('Argument "elementId" is not a string!');
    }

    if (typeof position !== 'number') {
        throw new TypeError('Argument "position" is not a number!');
    }

    // ...
};

Is there a way to properly test the parameters of this function without having to go through each data type? Like so:

it('should throw if argument "elementId" is an object', () => {
    const elementId = {};
    expect(() => {
        getRotation(elementId);
    }).toThrow();
});

it('should throw if argument "elementId" is boolean', () => {
    const elementId = true;
    expect(() => {
        getRotation(elementId);
    }).toThrow();
});

// ...

Upvotes: 0

Views: 1178

Answers (1)

Miguel Calderón
Miguel Calderón

Reputation: 3091

Something like this?:

it('should throw if argument "elementId" is not string or number', () => {
    [{}, true].forEach(elementId => {
        expect(() => {
            getRotation(elementId);
        }).toThrow();
    })
});

Upvotes: 1

Related Questions