【问题标题】:Unit test: How to mock mongoose code when using populate?单元测试:使用填充时如何模拟猫鼬代码?
【发布时间】:2018-04-26 14:50:55
【问题描述】:

我有一个带有静态函数的猫鼬模型,它通过 ID 查找员工文档并填充引用的 managerinterviewer 字段。

employeeSchema.statics.findAndPopulateById = function(id) {
  return this.findById(id)
    .populate("manager", "firstname lastname email")
    .populate("interviewer", "email")
    .then(employee => {
      if (!employee) {
        throw new errors.NotFoundError();
      }
      return employee;
    });
}

我知道当这个函数不包含填充链时如何测试它,但是填充部分让我陷入了循环。

具体来说,我正在尝试测试在找不到匹配记录时是否会引发NotFoundError 异常,但我很困惑如何模拟findById 方法以便可以在返回值上调用.populate()

如果我在没有.populate() 链的情况下测试这个方法,我会做类似的事情

let findByIdMock = sandbox.stub(Employee, 'findById');
findByIdMock.resolves(null);

return expect(Employee.findAndPopulateById('123')).to.be.rejectedWith(errors.NotFoundError);

但是,当涉及填充时,这种方法当然不起作用。我想我应该返回一个模拟查询或类似的东西,但我还需要能够在该模拟上再次调用填充或将其解析为一个承诺。

如何为此代码编写测试?我的职能应该采用不同的结构吗?

【问题讨论】:

    标签: node.js mongoose mocha.js sinon chai


    【解决方案1】:

    好吧,这最终比我预期的要容易,我只需要在我的最终 .populate().then() 之间添加对 .exec() 的调用,以使下面的测试正常工作。

    it("should throw not found exception if employee doesn't exist", () => {
      const mockQuery = {
        exec: sinon.stub().resolves(null)
      }
      mockQuery.populate = sinon.stub().returns(mockQuery);
    
      let findById = sandbox.stub(Employee, 'findById');
      findById.withArgs(mockId).returns(mockQuery);
    
      return expect(Employee.findAndPopulateById(mockId)).to.be.rejectedWith(errors.NotFoundError);
    });
    

    【讨论】:

      猜你喜欢
      • 2017-04-26
      • 2021-01-09
      • 2017-10-11
      • 2019-05-04
      • 2018-06-01
      • 2021-05-19
      • 2018-01-15
      • 2017-08-11
      • 2017-04-04
      相关资源
      最近更新 更多