Note that there are some explanatory texts on larger screens.

plurals
  1. POQUnit, Sinon.js & Backbone unit test frustration: sinon spy appears to fail to detect Backbone Model event callbacks
    primarykey
    data
    text
    <p>In the following unit test code:</p> <pre><code>TestModel = Backbone.Model.extend({ defaults: { 'selection': null }, initialize: function() { this.on('change:selection', this.doSomething); }, doSomething: function() { console.log("Something has been done."); } }); module("Test", { setup: function() { this.testModel = new TestModel(); } }); test("intra-model event bindings", function() { this.spy(this.testModel, 'doSomething'); ok(!this.testModel.doSomething.called); this.testModel.doSomething(); ok(this.testModel.doSomething.calledOnce); this.testModel.set('selection','something new'); ok(this.testModel.doSomething.calledTwice); //this test should past, but fails. Console shows two "Something has been done" logs. }); </code></pre> <p>The third ok fails, even though the function was effectively called from the backbone event binding, as demo'd by the console. </p> <p><img src="https://i.stack.imgur.com/UMUhR.png" alt="3rd test fails"> <img src="https://i.stack.imgur.com/AzTsm.png" alt="enter image description here"></p> <p>This is very frustrating and has shaken my confidence on whether sinon.js is suitable for testing my backbone app. Am I doing something wrong, or is this a problem with how sinon detects whether something has been called? Is there a workaround?</p> <p>EDIT: Here's a solution to my specific example, based on the monkey patch method of the accepted answer. While its a few lines of extra setup code in the test itself, (I don't need the module function any more) it gets the job done. Thanks, <code>mu is too short</code></p> <pre><code>test("intra-model event bindings", function() { var that = this; var init = TestModel.prototype.initialize; TestModel.prototype.initialize = function() { that.spy(this, 'doSomething'); init.call(this); }; this.testModel = new TestModel(); . . . // tests pass! }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload