Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one stub promise with sinon?

I have a data service with following function

function getInsureds(searchCriteria) {

    var deferred = $q.defer();

    insuredsSearch.get(searchCriteria,
        function (insureds) {
            deferred.resolve(insureds);
        },
        function (response) {
            deferred.reject(response);
        });

    return deferred.promise;
}

I want to test following function:

function search ()
{
  dataService
      .getInsureds(vm.searchCriteria)
      .then(function (response) {
           vm.searchCompleted = true;

            if (response.insureds.length > 100) {
              vm.searchResults = response.insureds.slice(0, 99);
            } else {
                vm.searchResults = response.insureds;
           }
       });
}

How would I stub the promise so that when I call getInsureds it would resolve the promise and return me the results immediately. I started like this (jasmine test), but I am stuck, as I don't know how to resolve the promise and pass in arguments needed.

it("search returns over 100 results searchResults should contain only 100 records ", function () {

    var results103 = new Array();

    for (var i = 0; i < 103; i++) {
        results103.push(i);
    }

    var fakeSearchForm = { $valid: true };
    var isSearchValidStub = sinon.stub(sut, "isSearchCriteriaValid").returns(true);

    var deferred = $q.defer();
    var promise = deferred.promise;
    var dsStub = sinon.stub(inSearchDataSvc, "getInsureds").returns(promise);

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

    //how do i call resolve  and pass in results103

    sut.performSearch(fakeSearchForm);

    sinon.assert.calledOnce(isSearchValidStub);
    sinon.assert.calledOnce(dsStub);

    sinon.assert.called(resolveStub);

    expect(sut.searchResults.length).toBe(100);

});
like image 463
epitka Avatar asked Dec 12 '13 22:12

epitka


People also ask

How do you stub a promise in Sinon?

To stub a promise with sinon and JavaScript, we can return a promise with a stub. import sinon from "sinon"; const sandbox = sinon. sandbox. create(); const promiseResolved = () => sandbox.

How does Sinon stub work?

Sinon replaces the whole request module (or part of it) during the test execution, making the stub available via require('request') and then restore it after the tests are finished? require('request') will return the same (object) reference, that was created inside the "request" module, every time it's called.

How do I stub an object in Sinon?

Stubbing functions in a deeply nested object getElementsByTagName as an example above. How can you stub that? The answer is surprisingly simple: var getElsStub = sinon.


3 Answers

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');
like image 139
Yu Huang Avatar answered Oct 09 '22 02:10

Yu Huang


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})
like image 22
Andreas Köberle Avatar answered Oct 09 '22 03:10

Andreas Köberle


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
like image 11
aH6y Avatar answered Oct 09 '22 03:10

aH6y