0

In the process of adding unit test coverage to existing javascript code we've encountered a case which we cannot seem to cover well, namely the code that checks for the callback's data to be undefined:

$.ajax({
    dataType: "json",
    url: someUrl,
    success: function(data) {
     if (typeof data === "undefined") {
        // *** How do I cover this line with jasmine? ***
     }
    },
    error: function () {
      // handle errors
    }
});

One of the possible answers would be that we cannot test this line, as data passed to the success function by jQuery.ajax cannot be undefined. Is that the case?

The reference mentions the data type of the passed data to be Anything, but I'm not sure if this does or does not mean data could be undefined, and if we could test the branch.

success

Type: Function( Anything data, String textStatus, jqXHR jqXHR )
Community
  • 1
  • 1
Spork
  • 1,631
  • 1
  • 21
  • 37
  • 2
    Why don't you create a quick example and test it? – bassxzero Dec 15 '17 at 14:54
  • 1
    if the URL called simply returns an empty reply it'd be an empty string, not undefined - since you're expecting json, that'd mean the jQuery function would've croaked on that, so the ERROR handler would be responsible. See the result on your console if you enter: JSON.parse(JSON.stringify(undefined)) – flowtron Dec 15 '17 at 14:57
  • @flowtron between the lines I'm reading the implication that the data in the success function is a JSON.parsed 'thing'. Is that the case? Can I expect that to always be the case for jQuery? – Spork Dec 15 '17 at 14:59
  • 1
    @Spork yes you can expect that as long as you define `dataType`. Either jQuery will call the error function if the data returned fails to parse as JSON or the data is valid JSON and the success function will be called. – bassxzero Dec 15 '17 at 15:03
  • In which case if it was valid json it would never be undefined. – Taplar Dec 15 '17 at 15:15
  • The answer to my question would then be that the docs are unnecessarily broad with 'Anything', and this implementation detail will never change -- jQuery uses JSON.parse and JSON.parse can only return an Object. – Spork Dec 15 '17 at 15:17
  • 1
    jQuery *only* uses json parse because of your dataType configuration. That's an important note. – Taplar Dec 15 '17 at 15:18

0 Answers0