使用 Mocha 和 Chai 为带有错误的函数编写测试用例

Writing test cases using Mocha and Chai for function with Error

我有一个简单的函数:

var moment = require('moment-timezone');

exports.splitIntoDays = function(from,to) {
    var timeIntervals = [];
    var interval = {};
    var start = moment(from);
    var end = moment(to);
    if(start.isAfter(end)) {
        throw new Error('From date ('+from+') is after To date ('+to+').Enter a valid date range.');
    }
    var initial = start;
    console.log("Before loop"+initial.format("YYYY/MM/DD-HH:mm:ss")+"  "+initial.diff(end,'hours'));
    while(end.diff(initial,'hours') > 24) {
        timeIntervals.push({"from" : initial.format("YYYY/MM/DD-HH:mm:ss"), "to" : initial.add(24,'hours').format("YYYY/MM/DD-HH:mm:ss")});
        initial = initial.add(1,'hours');
    }
    timeIntervals.push({"from" : initial.format("YYYY/MM/DD-HH:mm:ss"), "to" : end.format("YYYY/MM/DD-HH:mm:ss")});
    console.info(JSON.stringify(timeIntervals));
    return timeIntervals;
}

所以,如果我调用它 splitIntoDays('2014/09/13-10:00:00','2014/09/12-09:00:00'),我会得到以下响应:

Error: From date (2014/09/13-10:00:00) is after To date (2014/09/12-09:00:00).Enter a valid date range.

我使用 Mocha 和 Chai 编写了以下测试:

var expect = require("chai").expect;
var utils = require("../Utils.js");

describe("Utils", function(){
    describe("#splitIntoDays()", function(){
        it("equal", function () {
            var results = utils.splitIntoDays('2014/09/13-10:00:00','2014/09/12-09:00:00');
            expect(utils.splitIntoDays('2014/09/13-10:00:00','2014/09/12-09:00:00')).to.throw(new Error('From date (2014/09/13-10:00:00) is after To date (2014/09/12-09:00:00).Enter a valid date range.'));
        });
    });
});

但是,这个失败了。能帮我指出错误吗?

我也尝试了以下方法:

describe("Utils", function(){
    describe("#splitIntoDays()", function(){
        var error = new Error('From date (2014/09/13-10:00:00) is after To date (2014/09/12-09:00:00).Enter a valid date range.');
        it("equal", function () {
            expect(function(){
                utils.splitIntoDays('2014/09/13-10:00:00','2014/09/12-09:00:00');
            }).to.throw(error);
        });
    });
});

我得到以下信息:

AssertionError: expected [Function] to throw 'Error: From date (2014/09/13-10:00:00) is after To date (2014/09/12-09:00:00).Enter a valid date range.' but 'Error: From date (2014/09/13-10:00:00) is after To date (2014/09/12-09:00:00).Enter a valid date range.' was thrown

您可以在这里找到答案:Mocha / Chai expect.to.throw not catching thrown errors

基本上,您必须将函数传递给 expect()。现在您将结果传递给它。

编辑:粘贴我评论中有效的示例。

var expect = require('chai').expect;

describe('test', function(){

    var utils = {
        splitIntoDays : function(from, to){
            throw new Error('Invalid date range.');
        }
    }

    it('throws errors', function(){
        expect(utils.splitIntoDays.bind(utils, '2014/09/13-10:00:00', '2014/09/12-09:00:00')).to.throw(Error, 'Invalid date range.');
    });

});