【发布时间】:2015-03-21 18:56:43
【问题描述】:
在对以下代码进行单元测试时遇到了一些问题,由于它的编码方式,我不确定它是否可行。
storeModel.js
var storeSchema = new Schema({
storeId : { type: String, index: true},
storeName : String
});
var model = mongoose.model('store', storeSchema);
var findStoresById = function(ids, callback) {
model.find({ storeId: { $in: ids }}, function (err, result) {
if (err) callback(err);
callback(err, result);
});
};
return {
findStoresById: findStoresById,
schema: storeSchema,
model: model
};}();
我是这样测试的..
it('will call "findStoresById" and return matched values [storeId: 1111] ', function (done) {
storeModel.findStoresById(['1111'], function(err, store) {
assert.equal(store[0].storeId, '1111');
assert.equal(store[0].storeName, 'StoreName');
assert.equal(err, null);
done();
});
});
但是,当我在单独的函数中实现以下代码时出现问题:
get: function (req, res) {
if (req.query.storeIds) {
var ids = req.query.storeIds.split(',');
storeModel.findStoresById(ids, function(err, stores) {
if (err) {
return res.send(err);
}
if (_.isEmpty(stores)) {
var error = {
message: "No Results",
errorKey: "XXXX"
}
return res.status(404).json(error);
}
return res.json(stores);
}); ...
我如何对此进行单元测试,我不想模拟它,因为“findStoreById”中有需要测试的功能,或者是否需要重构?建议?
【问题讨论】:
-
我不明白为什么你的架构文件中需要这个
return { findStoresById: findStoresById, schema: storeSchema, model: model };}();。您可以在架构定义中将findStoresById函数定义为静态函数,并在您可以访问它的模型的任何地方调用它。storeSchema也可以作为模型的属性访问。 -
你能给我举个例子吗?
标签: node.js express mongoose mocha.js sinon