0

我有一个新Array.prototype方法

// tslint:disable-next-line: interface-name
interface Array<T> {
    random(): T;
    randomInRange(): T;
}

Array.prototype.random = function random() {
    if (this.length < 3) {
        throw new Error();
    }
    return this[Math.floor(Math.random() * this.length)];
};

如何编写测试用例来验证是否抛出错误?

// prototypes.test.ts
import './prototypes';

describe('Test Array.prototype.random method', () => {
    it('should return a random number from the array', () => {
        const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        const random = arr.random();
        const isNumberPresentInArray = arr.includes(random);

        expect(isNumberPresentInArray).toBe(true);
    });

    it('should throw error if there are less than 3 elements in the array', () => {
        const arr = [1, 2];
        expect(arr.random()).toThrow(new Error());
    });
});

我也试过了toThrowError,但没有运气。

4

0 回答 0