用mongoose对node.js进行unit testing的结构

我一直在开发与node.js几个月,但现在我开始一个新的项目,我想知道如何构build应用程序。

谈到unit testing时,我的问题就来了。 我将使用nodeunit编写unit testing。

另外我使用express来定义我的REST路由。

我想写我的代码访问数据库在两个“单独的”文件(他们会更多,显然,但我只是想简化代码)。 会有路线代码。

var mongoose = require('mongoose') , itemsService = require('./../../lib/services/items-service'); // GET '/items' exports.list = function(req, res) { itemsService.findAll({ start: req.query.start, size: req.query.size, cb: function(offers) { res.json(offers); } }); }; 

而且,正如我在那里使用的一个项目服务只是用来访问数据层。 我这样做是为了testingunit testing中的数据访问层。 这将是这样的事情:

 var mongoose = require('mongoose') , Item = require('./../mongoose-models').Item; exports.findAll = function(options) { var query = Offer .find({}); if (options.start && options.size) { query .limit(size) .skip(start) } query.exec(function(err, offers) { if (!err) { options.cb(offers); } }) }; 

这样,我可以检查unit testing,如果它工作正常,我可以在任何地方使用此代码。 我不确定是否正确完成的唯一方法是我传递callback函数以使用返回值的方式。

你怎么看?

谢谢!

是的,很容易! 你可以使用像摩卡这样的unit testing模块,也可以使用节点自己的assert或其他应用程序 。

作为示例模型的testing用例的示例:

 var ItemService = require('../../lib/services/items-service'); var should = require('should'); var mongoose = require('mongoose'); // We need a database connection mongoose.connect('mongodb://localhost/project-db-test'); // Now we write specs using the mocha BDD api describe('ItemService', function() { describe('#findAll( options )', function() { it('"args.size" returns the correct length', function( done ) { // Async test, the lone argument is the complete callback var _size = Math.round(Math.random() * 420)); ItemService.findAll({ size : _size, cb : function( result ) { should.exist(result); result.length.should.equal(_size); // etc. done(); // We call async test complete method } }, }); it('does something else...', function() { }); }); }); 

依此类推,令人厌恶。

然后,当你完成了你的testing – 假设你有$ npm install mocha $ ./node_modules/.bin/mocha – 那么你只需运行$ ./node_modules/.bin/mocha$ mocha如果你使用npm的-g标志。

取决于如何 直肠的 /详细你想成为真正的。 我一直build议,并且发现它更容易:首先写testing,以获得清晰的规格透视图。 然后写出实施对testing,任何额外的见解免费赠品。