在匿名函数中测试JavaScript函数 [英] Testing JavaScript functions inside anonymous functions

查看:41
本文介绍了在匿名函数中测试JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在下面测试 myInnerFunction ?

var val = function() {
    var myInnerfunction = function(input) {
        return input + ' I ADDED THIS';
    };
    return myInnerfunction('test value');
}();

由于 myInnerFunction 本质上是匿名执行的外部函数的私有成员,因此似乎无法从外部进行测试.

Because myInnerFunction is essentially a private member of the anonymously executed outer function, it doesn't seem like it is testable from the outside.

推荐答案

我认为对此的答案是(就像很多事情一样),我做错了.我定义为私有"功能的确需要进行测试.它只是私有的,因为我不想在实用程序api或类似的东西中公开它.但是它仍然可以通过我的应用程序名称空间公开.

I think my answer for this is (like so many things) that I'm doing it wrong. What I've defined as a 'private' function is really something that needs to be tested. It was only private because I didn't want to expose it within a utilities api or something like that. But it could still be exposed through my application namespace.

因此,在按需执行的匿名函数中,我只是将预定义函数作为事件处理程序附加到适当的DOM挂钩上.这些函数本身虽然没有与我的更多开放实用程序函数一起存储,但仍公共存储在与它们所处理的DOM结构相关联的我的名称空间的包中.这样我就可以找到它们并对其进行适当的测试.

So within the anonymous function that is executed on-dom-ready, I just attach my pre-defined functions as event handlers to the proper DOM hooks. The functions themselves, while not stored with my more open utilities functions, are still stored publicly within a package in my namespace associated with the DOM structure they are dealing with. This way I can get at them and test them appropriately.

这篇关于在匿名函数中测试JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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