Le seguenti due modalità di implementazione di ajaxRequest (1) (2) dovrebbero essere equivalenti.
Detto questo:Come spiare la richiesta jQuery AJAX?
- Perché l'test di unità (3) che verifica la richiamata è stato eseguito, riesce a (1) e non riesce a (2)?
- Come dovrei riscrivere il test (3) per spiare il callback di successo in (2)?
- Se provo a
stub jQuery.ajax
usando sinon e il codice (2) ottengo un errore. Come dovrei risolverlo?
Per ulteriori dettagli, vedere i commenti nel codice (3).
(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
});
+1 grazie per la procedura dettagliata. In realtà ora vorrei scrivere un test (3) per eseguirlo sul codice (2). Hai qualche idea di come farcela? Ho aggiornato la mia domanda. Grazie. –
Apparentemente, la chiamata .success() sarà deprecata in jQuery 1.8. Suggerisco che invece di usare il gelsomino per deridere il metodo ajax che si guarda a sinon.js (http://sinonjs.org/) che effettivamente prende in giro XHR nativo del tuo browser. Mi va benissimo. – badunk
Ho provato a 'stub jQuery.ajax', vedere la mia domanda, il codice (4). E ottengo e errore, perché? quale esempio di 'sinonjs.org' dovrei ottenere? –