How to create a stub for the ajax function using Jasmine BDD


I'm struggling to find any examples on how to fake an ajax call using Jasmine BDD?

I have a custom ajax function that works like so...

    url: 'JSON.php',
    dataType: 'json',
    onSuccess: function(resp) {

...and I've no idea how to create a stub to fake calling the actual ajax function.

I want to avoid calling the ajax function as it could slow down my test suite if a real ajax call to the server takes some time to respond and I've loads of specs in my test suite.

I've heard that you can use spyOn(namespace, 'ajax') but that is annoying straight away as it requires me to wrap my ajax function in an object just to use the spyOn function (but regardless I wasn't able to follow along as I couldn't find any specific examples to fake an ajax call).

I've also heard that you can use createSpy() but again the documentation isn't very helpful (neither is the corresponding wiki on GitHub).

Any help explaining how to use spies to create a fake ajax call would be greatly appreciated!

You can use SinonJS mocking framework, which has a build in fake server. You can easily use it with jasmine:

beforeEach(function() {
        server = sinon.fakeServer.create();
        server.respondWith([200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"])

Btw. if your ajax function is in the global namespace why not call spyOn(window, 'ajax')