最好的方法来测试使用变量从闭包的Javascript函数? [英] Best way to test Javascript functions that use variables from a closure?

查看:131
本文介绍了最好的方法来测试使用变量从闭包的Javascript函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我遇到的问题是我有一个函数在闭包中使用一个变量,当测试它返回一个引用的变量在它的范围。我的代码看起来类似于下面的:

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 };
    }
}

使用QUnit的测试代码如下:

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
});

问题是,即使将函数传递回测试,appendString函数仍然保存在应用程序范围内定义的theString。

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.

我已经设法通过使用eval创建一个函数的克隆,而不是直接使用它来克服这个问题:

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
});

但是我一直被教导避免eval,所以我想知道是否有更好的方法做这个?我在这里缺少一些东西,或者这是怎么实现的?

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?

推荐答案

是使用Eval来重新创建函数(根据我的例子)。虽然eval教会在这种情况下避免,它似乎是正确的事情。感谢您的帮助大家!

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!

这篇关于最好的方法来测试使用变量从闭包的Javascript函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆