Best way to test Javascript functions that use var

2019-06-27 23:05发布

问题:

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 the following:

var app = function() {
    var theString = "";

    //Appends ztvars onto the url passed into the function
    var appendString = function(url) {            
        if (theString.length === 0) {
            return url;
        }

        return url+theString;   
    };

    //Used for testing, returns the function appendPageVars
    this.returnFunctions = function() {
        return { appendString: appendString };
    }
}

And the testing code using QUnit looks like the following:

var theApp = new app();
appFunctions = theApp.returnFunctions();
test('appendString()', function() {
    var theString = "TestString";
    var theUrl = "http://www.test.com";
    equals(appFunctions.appendString(testUrl), theUrl+theString, "Checking the string appended to the url"); //Fails
});

The problem is that even when passing the function back to the test the appendString function still holds a reference to the theString defined inside the app scope.

I've managed to get around this problem by creating a clone of the function using eval rather than using it directly like so:

var theApp = new app();
appFunctions = theApp.returnFunctions();
test('appendString()', function() {
    var theString = "TestString";
    var theUrl = "http://www.test.com";
    eval("var appendString = "+appFunctions.appendString.toString());
    equals(appendString(testUrl), theUrl+theString, "Checking the string appended to the url"); //Passes
});

However I've always been taught to avoid eval and so I was wondering is there a better way to do this? Am I missing something here, or is this how it's supposed to be done?

回答1:

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

var App = function (theString) {
  theString = theString || ''; // optional argument

  var appendString = function (str) {
    return theString + str;
  };
  this.returnFunctions = function () {
    return { appendString: appendString };
  };
};

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


回答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!