简体   繁体   中英

How to expect throw with Mocha and Chai?

I am unable to find a solution to catching a thrown string with Mocha and Chai

Code being tested:

function SimpleDate(year, month, day) {
    if (!isValidDate(year, month, day)) {
        throw "invalid date";
    }
}

Test code:

it("returns 'invalid date' for year = 2023, month = 13, day = 55", function () {
    let actual = new DateUtils.SimpleDate(2013, 13, 55);
    //let expected ='invalid date';
    let expected = expect(() => DateUtils.SimpleDate(2013, 13, 55)).to.throw('invalid date');


    assert.equal(actual, expected);
});

I expect the test to pass, but the code I have tried fails saying 'Error: the string "invalid date" was thrown, throw an Error :)'

Turns out the solution is to define a wrapper function that calls the function you are testing, and then pass the wrapper to assert.throws

it("returns 'invalid date' for year = 2023, month = 13, day = 55", function () {
    let year = 2013,
        month = 13,
        day = 55;
    let expectedMessage = 'invalid date';
    let wrapper = function () {
        let x = DateUtils.SimpleDate(year, month, day);
    }

    assert.throws(wrapper, expectedMessage);
});

I believe you should throw an error rather than a string

function SimpleDate(year, month, day) {
        if (!isValidDate(year, month, day)) {
            throw new Error('invalid date');
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM