0

I want to ask somthing about jasmine spy . Normally i use spy like this

function getAuthrize(id) {
$.ajax({
    type: "GET",
    url: "/Account/LogOn" + id,
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});
}
spyOn($, "ajax");
getAuthrize(123);
expect($.ajax).toHaveBeenCalled();

but i want to know that what if i want to validate more things like ( the url called in ajax call is /Account/LogOn, type is 'Get' and so on .

Thanks in advance

Ancient
  • 2,857
  • 11
  • 49
  • 101

2 Answers2

0

For that you need to use a fake server object

Something like sinon.fakeServer

describe('view interactions', function(){
    beforeEach(function() {
        this.saveResponse = this.serverResponse.someObj.POST;
        this.server = sinon.fakeServer.create();
        this.server.respondWith(
              'POST',
               this.saveResponse.url,
               this.validResponse(this.saveResponse)
        );
    });

    afterEach(function() {
     this.server.restore();
    });
});

Need to make sure you have the this.serverResponse object defined

Sushanth --
  • 54,565
  • 8
  • 62
  • 98
  • i am not using `sinon` is there any way to do this in core `jasmine` ? – Ancient Jun 04 '13 at 06:02
  • I have not worked with jasmine on ajax requests. Maybe this should be of help .. http://stackoverflow.com/questions/4662641/how-do-i-verify-jquery-ajax-events-with-jasmine – Sushanth -- Jun 04 '13 at 06:04
0

To check if a spy was called with specific parameters you an use toHaveBeenCalledWith like this:

expect($.ajax).toHaveBeenCalled({
    type: "GET",
    url: "/Account/LogOn" + id,
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

But this will be become a very hard to read error when only one field in the JSON is wrong.

Another way is to use mostRecentCall.args:

var args = $.ajax.mostRecentCall.args[0];
expect(args.type).toEqual('GET')
expect(args.url).toEqual('/Account/LogOn123')

This will lead in a better readable errors as you can see which paramater was wrong.

Andreas Köberle
  • 98,250
  • 56
  • 262
  • 287