How to query jQuery AJAX?

The following two ways to implement ajaxRequest (1) (2) should be equivalent.
Having said that:

  • Why is unit test (3) executed, which checks the callback, succeeds in (1) and doesn't work (2)?
  • How can I rewrite test (3) to track a successful response in (2)?
  • If I try to stub jQuery.ajaxuse sinon and code (2), I get an error. How to fix it?

See comments in code (3) for more details.


(1)

ajaxRequest: function (message, callback) {
    return $.ajax({
        url: backendRouter.generate('feedback_send'),
        type: 'POST',
        dataType: 'json',
        data: {
            message: message
        },
        success: callback
    });
}

(2)

ajaxRequest: function (message, callback) {
    return $.ajax({
        url: backendRouter.generate('feedback_send'),
        type: 'POST',
        dataType: 'json',
        data: {
            message: message
        }
    }).success(callback);
}

(3)

it("should execute the callback function on success", function () {
    spyOn($, "ajax").andCallFake(function(options) {
        options.success();
    }); // If I use the code (2) I get the following error
        // TypeError: Object #<Object> has no method 'success'
    var callback = jasmine.createSpy();
    ajaxRequest('some message', callback);
    expect(callback).toHaveBeenCalled();
});

(4)

it("makes a GET request for todo items", function () {
    sinon.stub(jQuery, 'ajax');
    backendController.ajaxRequest('some message', sinon.spy()); 
    // Cannot call method 'success' of undefined
});
+5
source share
2 answers

Here's a walkthrough:

If you use the code in number 2, you call the ajax function in jquery:

return $.ajax({
  url: backendRouter.generate('feedback_send'),
  type: 'POST',
  dataType: 'json',
  data: {
    message: message
  }
...

jQuery jqHR, . :

...
}).success(callback);

, ajax. , $.ajax, .

// this is the value of the options parameter
{
    url: backendRouter.generate('feedback_send'),
    type: 'POST',
    dataType: 'json',
    data: {
        message: message
    }
}

, options.success, ! .

+4

jquery, sinonjs qunit ajax- .

jqueryspy

+1

All Articles