javascript - Mocking jquery selector and returning an html element -
i trying test javascript function requires element present in dom. below function trying test:
auction.save_scroll_state = function() { var user_agent = $window.navigator.useragent.tolowercase(); var is_android = user_agent.indexof("android") > -1; if (is_android) { var restore_pos = null; debugger if ($location.search().section == "items") { restore_pos = $('#all-items').scrolltop(); $('#all-items').one('scroll', function(){$('#all-items').scrollto(restore_pos)}); } else if ($location.search().section == "user_items"){ restore_pos = $('#your-items').scrolltop(); $('#your-items').one('scroll', function(){$('#your-items').scrollto(restore_pos)}); } } };
when run test , debugger type $('#all-items').length
returns 0
indicating element cannot found. trying form kind of jasime spy mock out jquery selector. test below:
it ('save_scroll_state android user_agent all-items', inject(function($bwappstate, $location, $window) { $window.navigator = {useragent: "mozilla/5.0 (linux; android 7.0; sm-g950f build/nrd90m) applewebkit/537.36 (khtml, gecko) chrome/58.0.3029.83 mobile safari/537.36"}; var items_div = $("<div id='all-items'></div>"); var jq_div_spy = spyon($.fn, 'html' ).and.returnvalue(items_div); var items_div_spy = spyon(items_div, 'scrolltop'); spyon($location, "search").and.returnvalue({section: 'items'}); $bwappstate.auction.save_scroll_state(); expect(items_div_spy).tohavebeencalled(); delete $window.nagivator; }));
the main goal make sure scrolltop()
gets called on html element has , id tag of id="all-items"
.
any appreciated
not ideally, as:
describe('scrolltop on .test', function(){ var scrolltopspy; beforeeach(function(){ scrolltopspy = jasmine.createspyobj('$-spy', ['scrolltop']); spyon(window, '$').and.callfake(function(selector){ if(selector == '.test') { return scrolltopspy; } else { return $(selector); } }); }); it('is called', function(){ $('.test').scrolltop(); expect($('.test').scrolltop).tohavebeencalled(); }); it('is not called', function(){ expect($('.test').scrolltop).not.tohavebeencalled(); }) })
please not call of scrolltop
on .test
performed, test ignorant of real .test
element existence in dom.
wiki
Comments
Post a Comment