javascript - Spy on function that's called on click event -
what doing wrong? trying spy on function get's called on elements click event test returns false.
spec:
describe('button', function() { before(function() { this.spy = sinon.spy(window, 'testmethod'); }); it('should call testmethod', function() { $('#testbtn').click(); expect(this.spy.called).to.equal(true); }); }); js:
$('#testbtn').on('click', testmethod); function testmethod() { return true; }
the problem due fact line:
$('#testbtn').on('click', testmethod); grabs reference testmethod before spy set. grabs reference original function, not spy, , not matter set spy on window.testmethod because function called on click event going original testmethod. have few options test work:
run
$('#testbtn').on('click', testmethod);after set spy. instance, put inbeforehook.change
$('#testbtn').on('click', testmethod);$('#testbtn').on('click', function () { testmethod(); });. anonymous function grab new referencetestmethodevery time click event handled. grab reference spy, once set it.
i've tested i'm saying here creating test replicates code , using 2 fixes above.
Comments
Post a Comment