简体   繁体   中英

sinon stub first api call and spy second api call

I have a method like this

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;
     });

I am stubbing the first fetch call like

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

Now to test success call

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

or failure

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

Have two questions:

  1. How can I spy that in case of first api error scenario, second fetch api is not called?
  2. How can I stub both fetch calls and test that last then is called when both fetch calls is resolved?

Thanks.

You can use the spy api on stubs. So if you make a stub of fetch you can use all the tools such as onFirstCall().resolves('some value') to return a promise as well as the spy properties like calledTwice .

For example to return two different promises and test that fetch was called twice you can:

 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> 

To test for rejected promises use stub.rejects('some values')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM