Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  197] [ 4]  / answers: 1 / hits: 9455  / 11 Years ago, tue, january 21, 2014, 12:00:00

I'm currently using enyo and I have a function on a component that takes a callback function and makes an ajax call, then calls the callback on success. I can't seem to figure out how to spy on the callback function.



enyo.kind({
name: 'Login',
isLoggedIn: function (callback) {
$.ajax({
url: '/checkLogin'
})
.done(function (data) {
/* Some logic here */
return callback.apply(null, data); //IF all goes well this should call the spy
})
.fail(function(){/*Fail Stuff*/});
}
....
});


For the test I have:



describe('Valid User', function() {
var ajaxSpy;
var loginTest = new Login();
beforeEach( function () {

ajaxSpy = spyOn($, 'ajax').andReturn({
done: function (fn ) {
fn();
},
fail: function (){}
});
});

it(should call the callback, function () {
var spy = jasmine.createSpy(spy);
loginTest.isLoggedIn(spy);
expect(spy).toHaveBeenCalled();
});
}


In this case when this runs the callback becomes undefined, I think it's probably because of the ajax spy intercepting it but I'm unsure how to fix it.


More From » ajax

 Answers
6

What the ajax call is doing is returning something call a promise.



There are various articles you can look on this regards:





But bottom line here are some sample code on how to achieve this:



spyOn( $, 'ajax' ).andCallFake( function (params) {
    
params.success({foo: 'bar'});

});

spyOn( $, ajax ).andCallFake( function (params) {

params.error({foo: bar});

});

[#48480] Tuesday, January 21, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dawnc

Total Points: 612
Total Questions: 94
Total Answers: 98

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
dawnc questions
Fri, Nov 26, 21, 00:00, 3 Years ago
Wed, Jul 15, 20, 00:00, 4 Years ago
Sun, Dec 15, 19, 00:00, 5 Years ago
Thu, May 30, 19, 00:00, 5 Years ago
;