Ecco il codice relativo alla richiesta di invio javascript (1).
Ecco il test per deridere la richiesta Ajax utilizzando jasmine (2).Come testare il Deferred Object fatto e fallito usando jasmine
Mi piacerebbe prendere in giro il comportamento del server. Qualche idea?
Vedere il commento in (1) e (2) per ulteriori dettagli.
P.S .:
In realtà, in entrambi i casi vengono chiamati l'Oggetto rinviato di FAke di FakeFunction.
(1)
submitForm: function() {
// the server execute fail only if message.val() is empty
// and I would like to mock this behaviour in (2)
backendController.submitForm(message.val()).done(this.onSuccess).fail(this.onError);
},
backendController.submitForm = function (message) {
return $.ajax({
url: 'some url',
type: 'POST',
dataType: 'json',
data: {
message: message
}
}).done(function() {
//some code;
});
};
(2)
describe('When Submit button handler fired', function() {
var submitFormSpy,
fakeFunction = function() {
this.done = function() {
return this;
};
this.fail = function() {
return this;
};
return this;
};
beforeEach(function() {
submitFormSpy = spyOn(backendController, 'submitForm').andCallFake(fakeFunction);
});
describe('if the message is empty', function() {
beforeEach(function() {
this.view.$el.find('#message').text('');
this.view.$el.find('form').submit();
});
it('backendController.submitForm and fail Deferred Object should be called', function() {
expect(submitFormSpy).toHaveBeenCalled();
// how should I test that fail Deferred Object is called?
});
});
describe('if the message is not empty', function() {
beforeEach(function() {
this.view.$el.find('#message').text('some text');
this.view.$el.find('form').submit();
});
it('backendController.submitForm should be called and the fail Deferred Object should be not called', function() {
expect(submitFormSpy).toHaveBeenCalled();
// how should I test that fail Deferred Object is not called?
});
});
});
Utilizzando un wrapper per il tuo chiamate AJAX renderà testare loro molto più facile. Vedi https://github.com/webadvanced/takeCommand – Paul
@Paul grazie per il tuo suggerimento. In realtà non capisco esattamente perché dovrei usare '/ webadvanced/takeCommand' dato che' $ .ajax' ha già ciò di cui ho bisogno. Potresti rispondermi scrivendo un codice di esempio? –
var spy = spyOn (class, "metodo"); actionThatCallsClassMethod(); expect (spy) .toHaveBeenCalled(); mi ha aiutato nel tuo esempio. – Aligned