recoup8063
recoup8063

Reputation: 4280

Jasmine with Karma: Ajax not working

Issue

I am running Javascript tests using Jasmine and Karma(As a test runner). The issue is that Ajax requests do not seam to be working.

If I run the following Jasmine test with Karma:

describe("Tests Ajax", function(done){
    it("does not work", function(){
        var options = {
            "url": "http://www.google.com",
            "method": "GET",
            "complete": function(data){
                console.log("Done!");
                done();
            }
        };

        $.ajax(options);
    });
});

I get the following Karma error:

        PhantomJS 1.9.8 (Windows 8) Tests Ajax does not work FAILED
            Error: Timeout - Async callback was not invoked within timeout specified
            by jasmine.DEFAULT_TIMEOUT_INTERVAL.

This means that the test took to long. I have tried setting jasmine.DEFAULT_TIMEOUT_INTERVAL to a longer time in beforeEach but this does not seam to change the results.

If I then run the above Ajax code in my browser it works and outputs "Done!" almost immediately.

The above results lead me to conclude that for some reason Ajax requests do not work when running Jasmine tests with Karma.

Additional Information

OS: Windows 8
Karma Test Browsers: PhantomJS(I have also tested with IE, Chrome, ChromeCanary, and Firefox, result are the same)
Karma Version: 0.12.31
Karma Jasmine Version: 0.3.2

Karma Config File
Github Repo

I am choosing not to use Jasmine Ajax because the code I am testing involves putting together various Ajax options correctly based on many other conditions and then interpreting the results. Thus completing a real Ajax request(To local files) is necessary.

Upvotes: 3

Views: 1650

Answers (1)

recoup8063
recoup8063

Reputation: 4280

To get around this issue I decided to run my tests with grunt-contrib-jasmine and have a server running in the background serving my content.

I used grunt-http-server for the server. I ran into 2 issues when setting this up. The first was that by default grunt-http-server does not allow Cross Origin Requests. To allow them you must add a headers option to the grunt task setup with the following headers:

{
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
}

The second issue I had was that grunt-http-server returns data no in the body field but in the responseText or responseJSON fields.

Upvotes: 2

Related Questions