Javascript 中的白盒测试 - 如何处理隐私?

发布于 2024-09-03 05:52:04 字数 436 浏览 11 评论 0原文

我正在为一个小型 Javascript 应用程序中的模块编写单元测试。为了保持界面简洁,一些实现细节由匿名函数(通常的 JS 模式以保护隐私)封闭。然而,在测试时我需要访问/模拟/验证私有部分。

我之前编写的大多数测试都是用 Python 编写的,其中没有真正的私有变量(成员、标识符,无论你想如何称呼它们)。人们只是通过前导下划线向用户暗示隐私,并在测试代码时随意忽略它。在静态类型的面向对象语言中,我认为可以通过将私有成员转换为受保护的对象并对要测试的对象进行子类化来使私有成员可访问测试。在 Javascript 中,后者不适用,而前者似乎是不好的做法。

我总是可以退回到黑盒测试并简单地检查最终结果。这是最简单、最干净的方法,但不幸的是,它不够详细,无法满足我的需求。

那么,是否有一种标准方法可以保持变量私有,同时仍然保留一些后门用于 Javascript 测试?

I'm writing unit tests for a module in a small Javascript application. In order to keep the interface clean, some of the implementation details are closed over by an anonymous function (the usual JS pattern for privacy). However, while testing I need to access/mock/verify the private parts.

Most of the tests I've written previously have been in Python, where there are no real private variables (members, identifiers, whatever you want to call them). One simply suggests privacy via a leading underscore for the users, and freely ignores it while testing the code. In statically typed OO languages I suppose one could make private members accessible to tests by converting them to be protected and subclassing the object to be tested. In Javascript, the latter doesn't apply, while the former seems like bad practice.

I could always fall back to black box testing and simply check the final results. It's the simplest and cleanest approach, but unfortunately not really detailed enough for my needs.

So, is there a standard way of keeping variables private while still retaining some backdoors for testing in Javascript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拥抱没勇气 2024-09-10 05:52:04

不,我不相信有。它基本上归结为您是否采用封闭方法并放弃白盒测试,或者进行白盒测试并为“私有”成员使用名称修饰。实际上不仅在 Python 中,在 javascript 中也有太多项目使用不那么神奇的下划线来装饰私有变量。所以在某种程度上,这已经是一个被广泛接受的问题解决方案。

如果您不希望这样并且确实需要白盒单元测试,那么您始终可以将测试集成到您的对象中。如果您对生产代码有单独的构建步骤(最小化、要求/提供分辨率等),那么您可以在此过程中删除测试函数。

No. I don't believe there is. It basically boils down to whether you take the closure approach and relinquish white box tests or do white box tests and use name decoration for "private" members. Actually not only in Python, but in javascript too many projects use the not so magic underscore to decorate privates. So in a way this is already a widely accepted solution to the problem.

If you don't want that and really, really need white-box unit testing, then you can always integrate the tests into your objects. If you have a separate build step for production code (minimization, require/provide-resolution, etc) then you can remove the test functions in this process.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文