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?