How does one stub promise with sinon?

后端 未结 5 2055
耶瑟儿~
耶瑟儿~ 2020-12-13 01:55

I have a data service with following function

function getInsureds(searchCriteria) {

    var deferred = $q.defer();

    insuredsSearch.get(searchCriteria,
         


        
相关标签:
5条回答
  • 2020-12-13 02:12

    At current sinon version v2.3.1, you can use stub.resolves(value) and stub.rejects(value) function

    For example, you can stub myClass.myFunction with following code

    sinon.stub(myClass, 'myFunction').resolves('the value you want to return');
    

    or

    sinon.stub(myClass, 'myFunction').rejects('the error information you want to return');
    
    0 讨论(0)
  • 2020-12-13 02:17

    I had a similar situation and the accepted answer and comments were not working, but along with this question they helped me solve this in the following way. I hope it is helpful for somebody.

    var Promise = require('bluebird');
    
    var deferred = Promise.defer();
    stub = sinon.stub(deferred, 'resolve').returns(deferred.promise);
    
    deferred.resolve({data: data});
    // or
    deferred.reject(new Error('fake error'));
    
    0 讨论(0)
  • 2020-12-13 02:21

    Also you can do something like this:

    import sinon from 'sinon';
    
    const sandbox = sinon.sandbox.create();
    
    const promiseResolved = () => sandbox.stub().returns(Promise.resolve('resolved'));
    const promiseRejected = () => sandbox.stub().returns(Promise.reject('rejected'));
    
    const x = (promise) => {
      return promise()
        .then((result) => console.log('result', result))
        .catch((error) => console.log('error', error))
    }
    
    x(promiseResolved); // resolved
    x(promiseRejected); // rejected
    
    0 讨论(0)
  • 2020-12-13 02:23

    There's one more alternative I found. Much pain free than other methods.

    You can use this npm package: sinon-stub-promise.

    It abstracts much of the details, so that you don't have to invent the wheel again. Helped my write my tests after struggling to simulate a promise for long.

    Hope it helps!

    0 讨论(0)
  • 2020-12-13 02:28

    You just have to resolve the promise before you call the search function. This way your stub will return a resolved promise and then will be called immediately. So instead of

    var resolveStub = sinon.stub(deferred, "resolve");
    

    you will resolve the deferred with your fake response data

    deferred.resolve({insureds: results103})
    
    0 讨论(0)
提交回复
热议问题