在Jest中测试函数参数数据类型

时间:2018-03-16 11:30:27

标签: unit-testing jest

我有以下功能:

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!');
    }

    // ...
};

有没有办法正确测试此函数的参数而无需遍历每种数据类型?像这样:

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();
});

// ...

1 个答案:

答案 0 :(得分:1)

这样的东西?:

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