Search code examples
jqueryrestqunitsinon

How can I unit test JS that uses a REST API?


So here's the deal: I have a single iframe in mypage.html. Using jQuery, I look at http://mysite.com/rest/foo (an exposed REST service) and get a XML response back, which contained a url. I set the iframe's src attribute to that URL.

The question, now, is how would I unit test this (using QUnit and Sinon.js)? I'm very new to unit testing in general, so I would like to hear some more experienced opinions and examples.

script.js:

$(document).ready(function() {

    function setUrl(url) 
    {
        $('iframe').attr('src', url);
    }

    function throwError() 
    {
        // Error handling
    }   

    function myCallback(response) 
    {
        var url = $(response).find("url");

        if (!url.text()) throwError();
        else setUrl(url.text());
    }

    function bar(restLocation, callback) 
    {       
        $.get("http://mysite.com/rest/" + restLocation, callback);
    }

    bar("foo", myCallback);
});

In particular, I'm wondering about the following things:

  1. I'm guessing I need to expose all of these functions to the global namespace in order to test them. Is this absolutely necessary, or is there a way to test them while still in the document.ready() function?

  2. Which function(s) should I test? bar() really only does one thing: make an AJAX call to /rest/foo/ and then call myCallback, while the others are helper methods (if I were writing this in Java or C#, they would probably be private)... should I test them too? The end user (the one who's viewing mypage.html) technically doesn't even have a choice of which REST address to point to.

  3. I imagine some suitable test cases might be

    • If a valid restLocation is passed to bar(), the iframe src should be set.
    • If an invalid restLocation is passed, the error must be handled (in the form of loading a 404 or something)
    • If the server is down, handle the error.
    • Anything else?

Unfortunately, if I try to do $('iframe').attr('src'), it returns undefined. If I try using prop(), I get an empty string. How would I check to see if src has been set properly?

Sorry for the long question. I'm just quite a bit confused on what kind of tests make a "good" unit test, and how one would test things in this situation.


Solution

  • First you should put the function passing into the read function into a named function, so you can call it like this

    $(document).ready(myFunction)
    

    Now you call myFunction into your test without the need to mock the $.ready function.

    The test will look like this:

    test( sets the iFrameUrl", function() {
      var server = sinon.fakeServer.create();
      server.respondWith('responseUrl');
      server.autoRespond = true;
      $('body').append('iframe')
      myFunction();
      equal($('iframe').attr('src'), 'responseUrl', 'iframe url')
    })