【问题标题】:Track how many times method has been called with Sinon/Mocha跟踪使用 Sinon/Mocha 调用方法的次数
【发布时间】:2018-07-08 14:28:44
【问题描述】:

我正在使用 Mocha/Sinon 编写测试,以确保我创建的 async tryAtMost 函数正在调用 Promise 并且仅重试该承诺 X 次数。

我的tryAtMost 函数如下所示:

  async tryAtMost(options, promise, maxRetries, retryInterval = 0) {
    return new Promise(async (resolve, reject) => {
      try {
        const res = await promise(options);
        if (res.statusCode == 200) {
          return resolve(res);
        } else {
          if (maxRetries > 0) {
            setTimeout(async () => {
              return await this.tryAtMost(options, promise, maxRetries - 1, retryInterval);
            }, retryInterval);
          } else {
            return reject('Ran out of retries, failing.');
          }
        }
      } catch (err) {
        return reject(err);
      }
    });
  }

我的 Mocha 测试为我的 promise 库创建了一个存根,我可以强制它返回我想要的任何状态代码。但是,我希望我的测试能够验证 tryAtMost 仅被调用 maxRetries + 1 次数。如果更熟悉 Mocha/Sinon 的人可以帮助我弄清楚如何做到这一点,我将不胜感激。

【问题讨论】:

    标签: node.js promise async-await mocha.js sinon


    【解决方案1】:

    Sinon spies 完美地为我解决了这个问题。我对我的包装方法做了一个间谍,我所要做的就是检查tryAtMostSpy.callCount。文档让它变得非常简单:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-25
      • 2019-03-24
      • 2018-08-28
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      相关资源
      最近更新 更多