如何在Sinon中使用多个参数存根mongoose方法?

问题描述 投票:2回答:1

我在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方法?

node.js unit-testing mongoose sinon sinon-chai
1个回答
0
投票

对像这样链接的单元测试函数只需链接stubspy实例,并验证它们是否被调用了期望值:

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
});
© www.soinside.com 2019 - 2024. All rights reserved.