我在Node.js中使用Mongoose,这是我的DAO方法。
function findPostsByCategoryId(categoryId, first, second) {
var sortingOrd = { 'createdAt': -1 };
return Post.find({ 'categoryId': categoryId }).sort(sortingOrd).skip(first).limit(second);
}
现在,我想在我的测试用例中使用Sinon来存储这样的方法。
describe('findPostsByCategoryId', function () {
it('should find post by category id', function () {
var stub = sinon.stub(Post, 'find');
stub.callsFake(() => {
return Promise.resolve(posts);
});
postDao.findPostsByCategoryId(1, 2, 3).then(response => {
assert.length(response, 1);
})
.catch((error) => {
assert.isDefined(error);
});
});
});
这给我一个错误,说“TypeError:Post.find(...)。sort不是一个函数”。
您能否阐明如何存根链接有多个功能的DAO方法?
对像这样链接的单元测试函数只需链接stub
和spy
实例,并验证它们是否被调用了期望值:
it('should find post by category id', function () {
const limitSpy = sinon.spy();
const skipStub = sinon.stub().returns({ limit: limitSpy });
const sortStub = sinon.stub().returns({ skip: skipStub });
const findStub = sinon.stub(Post, 'find').returns({ sort: sortStub });
postDao.findPostsByCategoryId(1, 2, 3);
sinon.assert.calledWithExactly(findStub, { 'categoryId': 1 }); // SUCCESS
sinon.assert.calledWithExactly(sortStub, { 'createdAt': -1 }); // SUCCESS
sinon.assert.calledWithExactly(skipStub, 2); // SUCCESS
sinon.assert.calledWithExactly(limitSpy, 3); // SUCCESS
});