Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test with jasmine a post call?

I'm trying to test a function with jasmine on javascript but i'm having a problem I haven't found any information to test a $.post or $.get function, also, because i'm using the done ($.deferred) which is asynchronous don't know how to handle it. The code is the following

function registrarUsuario(cel, eMail, nombre){
$.post(url, {
       phone_number : cel,
       email : eMail,
       name : nombre
       }).done(exitoso(data))} 

The question is, how do I test a $.post or $.get function with jasmine, and using the done function of the jqXHR.

The function exitoso(data) is the following:

function exitoso(data){
navigator.notification.alert('User register',
                             alertDismmissed(nombre, eMail, cel),
                             'Sucess');}

The reason I was having an error with data ErrorReference, but I had to change the code $.post(...).done as follow

.done(function(data){
 exitoso(data);
}

or also could have work as: .done( exitoso );

Thanks to Andreas Köberle for answering.

like image 324
Carlos Duque Yemail Avatar asked Nov 18 '25 17:11

Carlos Duque Yemail


1 Answers

So you can spy on $.post and return a resolved deferred:

var dfr = new $.Deferred();
dfr.resolve({data: "data"})
jasmine.spyOn($, 'post').andReturn(dfr)
registrarUsuario()

Another solution is to use sinonJs' fakeServer:

this.server = sinon.fakeServer.create();
this.server.respondWith('{data: "data"}');
server.autoRespond = true;
registrarUsuario()
like image 180
Andreas Köberle Avatar answered Nov 21 '25 07:11

Andreas Köberle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!