我对Node相对较新,正在使用knex和bookshelf进行项目开发。我在单元测试代码方面遇到了一些问题,不确定自己做错了什么。
基本上,我有一个名为VorcuProduct的模型,其代码如下:
var VorcuProduct = bs.Model.extend({
tableName: 'vorcu_products'
});
module.exports.VorcuProduct = VorcuProduct
这是一个保存VorcuProduct到数据库的函数,如果它在数据库中不存在的话。非常简单。实现这个功能的函数看起来像这样:
function subscribeToUpdates(productInformation, callback) {
model.VorcuProduct
.where({product_id: productInformation.product_id, store_id: productInformation.store_id})
.fetch()
.then(function(existing_model) {
if (existing_model == undefined) {
new model.VorcuProduct(productInformation)
.save()
.then(function(new_model) { callback(null, new_model)})
.catch(callback);
} else {
callback(null, existing_model)
}
})
}
哪种方法是在不访问数据库的情况下正确测试它的方式?我需要模拟fetch
返回一个模型或未定义(取决于测试),然后对save
也做同样的事情吗?我应该使用重装模块进行这项工作吗?如你所见我有点困惑,任何帮助都将不胜感激。
谢谢!