marcel
marcel

Reputation: 3272

Jasmine 2.0 how to handle ajax requests

I want to test a function, that includes a ajax request. The test should wait for the ajax-request to success/fail. Running the test doesn't work, because it doesn't wait right now.

this I want to be tested:

this.requestServerBoxId = function()
{
    //ajax-request
    $.ajax({
        url: this.host_addr+"/?getid="+this.name,
        type: 'POST',
        data: {_data:this._data},
        success: function(data) {
            return IdSuccess(data);
        },
        error: function(data){
            return false;
        }
    });
}
function IdSuccess(data){
   if(typeof data != undefined)
       return true;
    return false;
}

This is my test:

it("should call a function after ajax-success", function(){
    expect(this.Process.requestServerBoxId()).toBe(true);
});

I tried out spies, but I guess I'm using them wrong:

 spyOn($, 'ajax' ).and.returnValue(123);

I was hoping that this spy return 123 every time a ajax request is beeing made. But it doesn't work.

Upvotes: 3

Views: 9199

Answers (2)

Donald T
Donald T

Reputation: 10637

With Jasmine 2.0, there is a completely new API for testing ajax (and just about everything else).

Instead of:

spyOn($, 'ajax').and.returnValue(123);

Setup the beforeEach and afterEach methods before your it test:

beforeEach(function() {
  jasmine.Ajax.install();
  jasmine.Ajax.stubRequest('YOUR_URL_HERE').andReturn({
    responseText: 'YOUR_RAW_STUBBED_DATA_HERE'
  });
});

afterEach(function() {
  jasmine.Ajax.uninstall();
});

it('My Ajax Test', function() {
  // . . . code that makes an ajax request . . .
});

The it test will then execute its ajax request as expected.

Note that this makes your ajax call essentially synchronous but immediate.

Upvotes: 13

Gregg
Gregg

Reputation: 2638

You might want to look at something like https://github.com/pivotal/jasmine-ajax. This will let you stub out the ajax request and specify what you want it to return, behaving more like a normal ajax request.

The problem with spyOn in this instance is that the jQuery $.ajax method actually returns something more like a promise which you then have to send the correct result to, so a simple .and.returnValue won't do the right thing.

Upvotes: 1

Related Questions