一个存根如何与sinon一起承诺? [英] 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;
}
我想测试以下功能:
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,然后会立即调用然后
。因此,而不是
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})
这篇关于一个存根如何与sinon一起承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!