我如何使用Mocha和伊斯坦布尔编写出色的testing用例?

我正在尝试使用chai和Mocha为Mongoose模型函数编写unit testing用例。

模型function

function getDetails(parameter, fn) { Model.findOne({ parameter: parameter }) .lean() .exec(function(err, document) { if (err) { return fn(err, null); } return fn(err, document); }); }; 

unit testing用例

 describe('→ Database model functions.', function() { it('getDetails() - should fetch and return details from database', function(done) { model.getDetails(parameter, function(err, document) { expect(err).to.be.null; expect(document).not.to.be.null; expect(document).to.be.an('object'); done(); }); }); }); 

在使用istanbul运行代码覆盖率报告之后,我的分支覆盖率得分较低,因为以下代码块未被覆盖。

 if (err) { return fn(err, null); } 

据我所知,这对于未处理的exception,比如数据库closures等等,有一点儿难以捉摸。 这个错误也被devise为冒泡,这样的应用程序崩溃,我可以修复它。 我如何编写一个testing用例来解决这个问题? 或者说,我甚至应该试图掩盖这一点?

您可以使用模仿库(如Mockgoose)来testing错误情况 – 特别是,查看throwError选项,当尝试连接时会导致错误被引发 – 请参阅文档的这一部分 。 这应该是一个单独的testing用例,以上述testing。

正如@limelights在上面的评论中所说(正确地说,在我看来),最好避免在unit testing中使用真正的数据库。