Javascript 如何模拟Mongoose调用而不模拟exec中的回调逻辑?
我已经针对itemService函数Javascript 如何模拟Mongoose调用而不模拟exec中的回调逻辑?,javascript,mongoose,mocking,sinon,Javascript,Mongoose,Mocking,Sinon,我已经针对itemService函数getItemsForUser编写了一个测试,以对Mongoosefind调用返回的项目进行断言。但是,不管传入的用户对象是什么,我的测试当前都在通过,因为它模拟了传递给exec的整个回调 我的问题是,如何只模拟find和populate返回的项,而不跳过其余的逻辑,以便测试实际调用doUsersContainUser itemService.js item.js itemServiceTest.js 我正在使用sinon mongoose进行链式mongoo
getItemsForUser
编写了一个测试,以对Mongoosefind
调用返回的项目进行断言。但是,不管传入的用户对象是什么,我的测试当前都在通过,因为它模拟了传递给exec
的整个回调
我的问题是,如何只模拟find
和populate
返回的项,而不跳过其余的逻辑,以便测试实际调用doUsersContainUser
itemService.js
item.js
itemServiceTest.js
我正在使用sinon mongoose进行链式mongoose呼叫。您是如何要求doUsersContainUser功能和
项目的
?请提供code@slideshowp2现在包括代码
const Item = require('../models/item');
exports.getItemsForUser= function(user, cb)
{
Item.find({}).populate('users').exec(function (err, itemList)
{
if (err) { throw next(err) }
else {
cb(null, itemList.filter(i=> doUsersContainUser(i, user._id));
}
});
};
function doUsersContainUser(item, userId) {
return item.users.some(u => hasValue(u, 'user', userId))
}
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ItemSchema = new Schema({
users: [{ type: Schema.Types.ObjectId, ref: 'User' }]
});
module.exports = mongoose.model('Item', ItemSchema );
it('should return all items for user', function () {
const allItems = itemsData.allItemsPopulated();
const user = { id: 10001 };
sinon.mock(Item).expects('find')
.chain('populate', 'users')
.chain('exec')
.returns(null, allItems);
itemService.getItemsForUser(user, function(err, result) {
assert.strictEqual(result, allItems);
});
});