一个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})
相关文章