So, the problem that I encountered is a function that uses a variable in closure and when testing it returns a reference to the variable in it. My code looks something like this:
var app = function() { var theString = "";
And the testing code using QUnit is as follows:
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");
The problem is that even when passing the function back to the test, the appendString function still contains a link to a string defined inside the application scope.
I managed to get around this problem by creating a function clone using eval, and not using it directly like this:
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");
However, I was always taught to avoid eval, and so I was wondering if there is a better way to do this? Am I missing something here, or is it how it should be done?
source share