Any better way than setTimeout to wait for asnyc callback when testing JavaScript?

Given this code:

showForm = function (url) { return $.get(url, function (html) { $('body').append(); }); }; 

When using sinon.js , jQuery.mockjax.js and expect.js , I have the following passing test:

 it("showForm calls jQuery.append", function () { $.mockjax({ url: '/fake' }); var spy = sinon.spy($.fn, "append"); presenter.showForm('/fake'); setTimeout(function () { expect(spy.called).to.be.equal(true); }, 1000); }); 

Using the setTimeout function to wait for a callback from the asynchronous smell of $.get bad, and this will slow down my test suite if I do too much.

However, I feel that the intention is clear enough, and it looks like he is definitely checking what I want.

Is there a better way and can you explain what is happening in your answer?

+4
source share
3 answers

Pass an anonymous function to show the form as a parameter and call it in the callback after adding. To provide a call to it, you can make a $ .ajax request, which also includes an error callback.

This method is called exactly when the request for receipt ends without too much time or is called too early.

 showForm = function (url, callback) { return $.get(url, function (html) { $('body').append(); if(callback != undefined) callback(); }); }; it("showForm calls jQuery.append", function () { $.mockjax({ url: '/fake' }); var spy = sinon.spy($.fn, "append"); presenter.showForm('/fake', function (){ expect(spy.called).to.be.equal(true); }); }); 
+3
source

You should use fakeServer sinons . This will call your ajax callback right away when the $.ajax call was made. See jsFiddle

 before(function(){ var server = sinon.fakeServer.create(); server.respondWith('response'); }) it("showForm calls jQuery.append", function () { var spy = sinon.spy($.fn, "append"); presenter.showForm('/fake'); server.respond(); expect(spy.called).to.be.equal(true); }); 
+1
source

Use the $ .doTimeout plugin

Check the following documentation.

http://benalman.com/projects/jquery-dotimeout-plugin/

Hope this helps

0
source

Source: https://habr.com/ru/post/1492704/


All Articles