【问题标题】:How to Mock Mongo Cursor object with Node.js and Sinon如何使用 Node.js 和 Sinon 模拟 Mongo 光标对象
【发布时间】:2021-09-29 16:14:23
【问题描述】:

我需要为一些旧代码添加单元测试覆盖率,并且难以创建一个模拟 Cursor object,这将允许链接项目、限制、跳过、toArray,如下所示。

collection.find({}, (err, res) => {
......
    const results = res.project(projection)
                       .limit(limitCount)
                       .skip(skipCount)
                       .toArray()

我之前使用响应对象上可用的 toArray 模拟了 DB/collection/find(如下所示),但不确定如何处理上述其他游标“值”的链接。

            let fakeFind = () => {
                return {
                    toArray: () => {
                        return Promise.resolve(testCustomerRecord);
                    }
                };
            }

            let stubFind = sinon.stub().callsFake(fakeFind);
            
            let mockDb = {
                collection: () => {
                    return {
                        find: stubFind
                    };
                }
            };

我尝试将它们添加为属性、函数,但得到如下错误:

TypeError: item.project(...).limit 不是函数

欢迎任何建议!

【问题讨论】:

    标签: node.js mongodb sinon


    【解决方案1】:

    stub.returnsThis(); 方法允许您存根链调用。

    例如

    import sinon from 'sinon';
    
    // service under test
    const service = {
      find(db) {
        return new Promise((resolve) => {
          db.collection.find({}, (err, res) => {
            const results = res.project({ a: 1 }).limit(10).skip(0).toArray();
            resolve(results);
          });
        });
      },
    };
    
    describe('68483854', () => {
      it('should pass', async () => {
        const mockRes = {
          project: sinon.stub().returnsThis(),
          limit: sinon.stub().returnsThis(),
          skip: sinon.stub().returnsThis(),
          toArray: sinon.stub().returns('mock data'),
        };
        const mockDb = {
          collection: {
            find: sinon.stub().callsFake((where, callback) => {
              callback(null, mockRes);
            }),
          },
        };
        const actual = await service.find(mockDb);
        sinon.assert.match(actual, 'mock data');
        sinon.assert.calledWithExactly(mockRes.project, { a: 1 });
        sinon.assert.calledWithExactly(mockRes.limit, 10);
        sinon.assert.calledWithExactly(mockRes.skip, 0);
        sinon.assert.calledOnce(mockRes.toArray);
      });
    });
    

    【讨论】:

    • 谢谢,很惊讶我之前在搜索中没有遇到过!
    猜你喜欢
    • 2020-10-24
    • 1970-01-01
    • 2016-05-10
    • 2018-06-16
    • 2018-04-12
    • 2016-10-18
    • 2017-10-08
    • 2021-09-22
    相关资源
    最近更新 更多