我有以下简单的功能:
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
答案 0 :(得分:2)
您可以在此处找到答案: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.');
});
});