[英]Structure for unit testing on node.js with mongoose
我已經使用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);
}
})
};
這樣,我可以檢查單元測試是否正常工作,並且可以在任何需要的地方使用此代碼。 我不確定它是否正確完成的唯一事情是我傳遞回調函數以使用返回值的方式。
你怎么看?
謝謝!
是的,很容易! 您可以使用單元測試模塊(例如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() {
});
});
});
以此類推,廣告惡心。
然后,當您編寫$ ./node_modules/.bin/mocha
測試后-假設您已經$ npm install mocha
$ ./node_modules/.bin/mocha
那么您只需運行$ ./node_modules/.bin/mocha
或$ mocha
如果您使用了npm的-g標志)。
取決於如何 直腸的 / detailed你想成為真的。 我總是被建議這樣做,並且發現它更容易:首先編寫測試,以清楚地了解規格說明。 然后針對測試編寫實現,並提供免費的贈品。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.