首页 > 解决方案 > 用 sinon 进行单元测试

问题描述

我正在尝试模拟以下代码:

 model.findAndCountAll({
            pos: start
        }).then((data) => {
         this.success(....);
        }).error(error => {
            this.error(error, this.constants.HTTP_CODE_INTERNAL_SERVER_ERROR)
        })

下面是模拟上述代码的代码:

const findAndCountAll =  sinon.stub(model, 'findAndCountAll');
          findAndCountAll.withArgs().returns(new Promise((resolve, reject) => {
            resolve(data);
          }));

如果我从要模拟的代码中删除错误部分,它会起作用,否则会出现以下错误:

 TypeError: model.findAndCountAll(...).then(...).error is not a function

标签: node.js

解决方案


Promise没有功能error,你想要catch

model.findAndCountAll(...)
  .then(data => { ... })
  .catch(err => { ... })

推荐阅读