Testing, do I need to add more Return statements to my functions?

49 Views Asked by At

I would like to start using a test framework, mocha + expect seem good to me.

Say i have this function,

/*
 * Hides or shows loading .gif
 * show : boolean
 */
function loadingMsg(show) {
    var $loader = $("#loader");
    if(show){
        $loader.show();
    }
    else{
        $loader.hide();
    }
}

To make it testable, do I need to add Return statements like below?

/*
 * Hides or shows loading .gif
 * show : boolean
 */
function loadingMsg(show) {
    var $loader = $("#loader");
    if($loader){
        if(show){
            $loader.show();
            return "loader shown";
        }
        else{
            $loader.hide();
            return "loader shown";
        }
    }
    else {
        return "$loader undefined";
    }
}

Or should I be testing the dom element "loader"?

2

There are 2 best solutions below

1
On

No you don't.

Instead check for loader element display property in the DOM.

Update after comment:

haven't used much of mocha but when in comes to testing UI, its similar fashion almost in every framework or libarary. Look for elements in the DOM using jQuery or any selector lib you have available and check their content if they are as desired. In your case you will check if loader element is display block or display none.

something like when loader is shown

expect($('#loader').css('display')).toBe('block');

when loader is hidden

expect($('#loader').css('display')).toBe('none');
0
On

A best practice is: your tests shouldn't require your code-under-test to be modified such that they can either pass/fail. So you shouldn't add return statements like you've suggested, you also shouldn't have 'test' flags that can be passed into a function to enable some special test state.

So the simple answer is: no, you shouldn't add return statements.

But just the posing of the question itself sounds to me like maybe you're new to DOM testing? It sounds like you wish to unit test the code you've sampled there, perhaps outside of the rest of your app?

Assuming that's true, then maybe you should look at something like mocha-jsdom; I'd expect you'd then be able to write a test like:

describe('mocha tests', function () {
  var $;
  jsdom();

  before(function () {
    $ = require('jquery'); // Sets up jQuery to be available
  });

  describe('with visible=false', function() {
    it('shows the loader', function () {
      document.body.innerHTML = '<div id="loader">My faked loader</div>'
      loadingMsg(false);
      expect($("#loader:visible").length).eql(0)
    });
  });
});

Note: I can't promise that code snippet will work, just a example (and mostly stolen from mocha-jsdom's page!).