8

几个月来我一直在使用 node.js 进行开发,但现在我正在开始一个新项目,我想知道如何构建应用程序。

当谈到单元测试时,我的问题就出现了。我将使用 nodeunit 来编写单元测试。

我也使用 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);
        }
   });  
  };

而且,正如我在那里使用的那样,项目服务仅用于访问数据层。我这样做是为了在单元测试中仅测试数据访问层。它会是这样的:

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);
            }
    })
};

这样,我可以通过单元测试检查它是否正常工作,并且我可以在任何我想要的地方使用此代码。我唯一不确定是否正确完成的是我传递回调函数以使用返回值的方式。

你怎么看?

谢谢!

4

1 回答 1

2

是的,很容易!您可以使用mocha之类的单元测试模块以及节点自己的 assert 或其他诸如should之类的模块。

作为示例模型的测试用例示例:

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() {

    });

  });

});

等等,令人作呕。

然后,当你完成编写测试时——假设你已经$ npm install mocha'd——那么你只需运行$ ./node_modules/.bin/mocha或者$ mocha如果你使用了 npm 的 -g 标志。

取决于如何直肠/详细你想成为真的。我一直被建议并且发现更容易: 首先编写测试,以获得清晰的规范视角。然后针对测试编写实现,任何额外的见解都是免费的。

于 2012-12-29T02:48:23.720 回答