【问题标题】:getById() returns undefined PromisegetById() 返回未定义的 Promise
【发布时间】:2017-09-22 07:18:28
【问题描述】:

我的 Sequelize 模型中有以下类方法:

getById(id) {
      return new Promise((resolve, reject) => {
          var Conference = sequelize.models.conference;
          Conference.findById(id).then(function(conference) {
              if (_.isObject(conference)) {
                  resolve(conference);
              } else {
                  throw new ResourceNotFound(conference.name, {id: id});
              }
          }).catch(function(err) {
              reject(err);
          });
      });
  }

现在我想用 chai 测试我的方法。但是现在当我执行Conference.getById(confereceId) 时,我得到了以下信息:

Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }

这是正确的,我如何用 chai 断言它的结果?

【问题讨论】:

标签: node.js promise sequelize.js models chai


【解决方案1】:

您的Conference.getById(confereceId) 调用返回一个promise,因此您应该首先通过then 解决promise,然后使用chai 断言它的结果,如下所示:

const assert = require('chai').assert;

Conference
  .getById(confereceId)
  .then(conf => {
    assert.isObject(conf);
    // ...other assertions
  }, err => {
    assert.isOk(false, 'conference not found!');
    // no conference found, fail assertion when it should be there
  });

【讨论】:

  • 如果then() 中的任何断言失败,它们也会触发catch(),这可能会导致混淆错误。
  • 没错,我编辑了答案以使用.then(onFulfilled, onRejected) 而不是.then(onFulfilled).catch(onRejected) 来解决这个问题。
  • 是的,我看到了,+1:D
猜你喜欢
  • 2017-10-31
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-27
  • 2021-06-03
  • 2015-11-10
  • 1970-01-01
相关资源
最近更新 更多