Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to unit test internal functions in jquery plugin?

in a jQuery plugin i have created helper functions, like this

(function($) {

  var someHelperFunction = function(s, d) {
    return s*d;
  }
  var someOtherHelperFunction = function(s) {
    return s*2;
  }

// here goes the normal plugin code

})(jQuery);

now I want to call someHelperFunction from the outside, to be able to unit test it, is that possible somehow?

like image 299
JohnSmith Avatar asked Mar 30 '11 19:03

JohnSmith


2 Answers

Per this related question, I'd say just test the external interface.

But if you must test these methods in isolation, you'll have to test "copies" of them outside of the context of their deployment as internal methods. In other words, create an object in which they are not inaccessible to client code, and then cobble those versions together with your outer script in a pre-process. Sounds like a lot of work, but hey, that's the point of hiding methods, right? (To make them unreachable.)

like image 164
harpo Avatar answered Nov 08 '22 01:11

harpo


If the internal functions need testing that's a good indicator that they should maybe be in a separate module somewhere and injected as dependencies and used within your objects public interface implementation. That's the more "testable" way to do it.

var myActualImplementationTestTheHellOutOfMe = function(s, d) {

    return s*d;

}

(function($, helper) {

  var someHelperFunction = function(s, d) {
    return helper(s, d);
  }
  var someOtherHelperFunction = function(s) {
    return s*2;
  }

// here goes the normal plugin code

})(jQuery, myActualImplementationTestTheHellOutOfMe);
like image 34
Derek Reynolds Avatar answered Nov 08 '22 03:11

Derek Reynolds