Using Sinon.js and preventing my application server from calling

A fairly simple question:

I want us to check a javascript piece of sinon.js to make sure that it calls the $.ajax method, doing two things:

  • I do not want to click on the server
  • I want to combine the response from the server

so here's js:

  $.ajax url: "/tickets/id.json" dataType: 'json' .done (data) => HandlebarsTemplates["tickets/popup_title"] data 

and here is my test:

 describe 'PopupDisplayer', -> beforeEach -> loadFixtures 'popup_displayer' new PopupDisplayer @title_stub = sinon.stub( HandlebarsTemplates, "tickets/popup_title") @jquery_stub = sinon.stub(jQuery, 'ajax').yieldsTo('done', {}) //This triggers the ajax call $('.popupable .title').mouseenter() afterEach -> HandlebarsTemplates['tickets/popup_title'].restore() HandlebarsTemplates['tickets/popup_content'].restore() jQuery.ajax.restore() @server.restore() it 'renders the title with the data returned from the server', -> expect(@title_stub).toHaveBeenCalledWith( {}) 

This test failed, but with the following exception:

 TypeError: ajax expected to yield to 'done', but no object with such a property was passed. Received [[object Object]] 

So, I think I'm wondering if I can make a jQuery query layout to get an answer that can successfully answer the .done call, apparently I don't understand defferedObject() enough.

+4
source share
1 answer

To mock the server response, you want to drown out the return value of $.ajax :

  ... @jquery_stub = sinon.stub(jQuery, 'ajax').returns done: (callback) -> callback {...} # your object here ... 

Note that this only mutes the done callback. If you want to test different behavior, you probably need to implement other handlers ( fail , then , etc.).

You can also return the actual jQuery Deferred object:

  ... @deferred = new jQuery.Deferred @jquery_stub = sinon.stub(jQuery, 'ajax').returns(deferred) ... 

In this case, you will need to explicitly call the returned Deferred before executing the tests:

  ... @deferred.resolveWith(null, [{}]) # your object here ... 
+3
source

All Articles