【问题标题】:sinon stub first api call and spy second api callsinon stub 第一个 api 调用和 spy 第二个 api 调用
【发布时间】:2018-11-10 02:12:35
【问题描述】:

我有这样的方法

fetch('first api')
    .then(resp => {
        if (resp.status === '500') {
            return Promise.reject('some error');
        }
        return fetch('second api');
     })
     .then(resp => {
         // do something;
     })
     .catch(resp => {
        // do something;
     });

我正在对第一个 fetch 调用进行存根

const stub = sinon.stub(window, 'fetch');

现在测试成功调用

stub.withArgs('first api').returns(Promise.resolve(//window.Response));

或失败

stub.withArgs('first api').returns(Promise.reject(//window.Response));

有两个问题:

  1. 我如何spy 在第一个 api 错误情况下不调用第二个 fetch api?
  2. 如何存根两个 fetch 调用并测试在两个 fetch 调用都解决后最后一个 then 是否被调用?

谢谢。

【问题讨论】:

    标签: javascript fetch sinon


    【解决方案1】:

    您可以在存根上使用 spy api。因此,如果您创建了 fetch 的存根,您可以使用所有工具(例如 onFirstCall().resolves('some value'))来返回承诺以及像 calledTwice 这样的间谍属性。

    例如,返回两个不同的 Promise 并测试 fetch 是否被调用了两次:

    function run(){
      return fetch('first api')
        .then(resp => {
            if (resp.status === '500') {
                return Promise.reject('some error');
            }
            return fetch('second api');
         })
         .then(resp => {
             // do something;
         })
         .catch(resp => {
            // do something;
         });
    }
    
    let stub = sinon.stub(window, 'fetch')
    stub.onFirstCall().resolves("testing first")
    stub.onSecondCall().resolves("testing second")
    
    run().then(()=> console.log("called twice: ", stub.calledTwice))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/7.1.1/sinon.min.js"></script>

    要测试被拒绝的承诺,请使用stub.rejects('some values')

    【讨论】:

      猜你喜欢
      • 2019-11-30
      • 2016-09-12
      • 1970-01-01
      • 2022-07-03
      • 2020-08-01
      • 2019-11-26
      • 2019-12-14
      • 1970-01-01
      • 2020-10-19
      相关资源
      最近更新 更多