Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

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

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...