【问题标题】:sinon.stub().returns specified for each call rather then oncesinon.stub().returns 为每个调用指定而不是一次
【发布时间】:2017-07-14 22:03:37
【问题描述】:

下面我有一些代码来演示我如何测试/存根promise,useSpyPromise 下面的函数使用参数promise spyPromise。我试图弄清楚如何指定存根在第一次调用 (Promise.resolve(['hasLength']) 时返回一个承诺,并在第二次调用 (Promise.resolve([]) 时解决不同的承诺。

let spyPromise = sinon.stub().returns(Promise.resolve(['hasLength']))

function useSpyPromise (spyPromise) {
  let promiseOne = spyPromise
    .then(d => {
      if (d.length === 0) throw new Error('d 0')
      return d
    })

  let promiseTwo = spyPromise
    .then(d => {
      if (d.length === 1) throw new Error('d 1')
      return d
    })

  return {promiseOne, promiseTwo}  
}

【问题讨论】:

    标签: javascript testing promise sinon


    【解决方案1】:

    很难准确地说出你想要什么,但有一件事似乎很确定;提供测试是同步的 - 即。没有进一步的承诺 - 那么你不需要promise1promise2,只需要return spyPromise.then(...)

    您可能只想让行为完全由d.length 决定,在这种情况下,它就像这样简单:

    function useSpyPromise(spyPromise) {
        return spyPromise.then(d => {
            if(d.length <= 1) {
                throw new Error('d ' + d.length);
            }
            return d;
        });
    }
    

    但是,如果您真的想要考虑调用函数的次数,那么可能是这样的:

    var count = 0;
    function useSpyPromise(spyPromise) {
        count += 1;
        return spyPromise.then(d => {
            if(count === 0 && d.length === 0) {
                throw new Error('d 0');
            if(count === 1 && d.length === 1) {
                throw new Error('d ' + d.length);
            }
            return d;
        });
    }
    

    这是一件很奇怪的事情,但也许这是您的应用程序需要的。我说不清楚。

    无论如何,这不是故事的结局。您可以通过多种方式制定测试。例如应该抛出count &gt; 1 条件吗?问题没有这么说,但是你考虑过那些案例吗?

    您所写的内容取决于您想要的精确行为。

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多