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:

  1. run $('#testbtn').on('click', testmethod); after set spy. instance, put in before hook.

  2. change $('#testbtn').on('click', testmethod); $('#testbtn').on('click', function () { testmethod(); });. anonymous function grab new reference testmethod every 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

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -