一个stub如何与sinon约定? [英] How does one stub promise with sinon?

查看:27
本文介绍了一个stub如何与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;
}

我想测试以下功能:

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

我将如何对承诺进行存根,以便在我调用 getInsureds 时它会解决承诺并立即返回结果.我是这样开始的(茉莉花测试),但我被卡住了,因为我不知道如何解决承诺并传递所需的参数.

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

});

推荐答案

你只需要在调用搜索函数之前解决promise.这样,您的存根将返回已解决的承诺,并且 then 将立即被调用.所以不是

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

这篇关于一个stub如何与sinon约定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆