Question

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.

Was it helpful?

Solution

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"});
      
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top