Skip to content Skip to sidebar Skip to footer

Unit Testing Jquery Getjson Function Errors With The Fail Method, Using Jasmine And Karma

I've written a unit test for a function that calls the jQuery getJSON method. The only thing that I'm testing is that it is called with the expected URL. My unit test uses a Jasmin

Solution 1:

In your function getDataFromApi you are chaining the call of fail after done but, in the mocked version of done, it returns nothing(undefined), so, you get TypeError: Cannot read property 'fail' of undefined.

You can make the done function to return an object with a fail property that is a function.

beforeEach(function() {
  spyOn($, "getJSON").and.callFake(function() {
    return {
      done: function() {
        return { fail: function() {} };
      }
    };
  });
});

Or, one line ES6 version spyOn($, "getJSON").and.callFake(() => ({ done: () => ({fail: () => {}}) }));

Or, if you are planning to do more in your tests, like testing success or failed responses, probably returning a jQuery Deferred can help you

beforeEach(function() {
  spyOn($, "getJSON").and.callFake(function() {
    const deferred = $.Deferred();

    deferred.resolve({'success': true});

    return deferred;
  });
});

Calling deferred.reject({'success': false}); will give you the chance to test for errors.

Hope it helps

Post a Comment for "Unit Testing Jquery Getjson Function Errors With The Fail Method, Using Jasmine And Karma"