Skip to content Skip to sidebar Skip to footer

Best Way To Test Javascript Functions That Use Variables From A Closure?

So the problem I'm having is I have a function which uses a variable in a closure and when testing it it returns a reference to the variable in it's scope. My code looks similar to

Solution 1:

What you need is dependency injection when you provide the object with a mock object.

varApp = function (theString) {
  theString = theString || ''; // optional argumentvar appendString = function (str) {
    return theString + str;
  };
  this.returnFunctions = function () {
    return { appendString: appendString };
  };
};

test('appendString()', function () {
  var app = newApp('TestString');
  var fns = app.returnFunctions();
  equals(fns.appendString('test'), 'TestStringtest', ...);
});

Solution 2:

So as far as I can tell the answer is to use Eval to recreate the function (as per my example). Although eval is taught to be avoided in this case it appears to be the right thing to do. Thanks for your help everyone!

Post a Comment for "Best Way To Test Javascript Functions That Use Variables From A Closure?"