我应该测试 Javascript 插件的私有函数吗?
我正在尝试编写测试驱动的 Javascript。我知道,测试每个功能至关重要。但我遇到了一个绊脚石,因为我正在编写的插件需要有一些私有函数。我无法窥探它们是如何运作的。如果我想让我的代码得到良好的测试而不改变太多的结构,我需要做什么? (尽管在限制范围内,我可以公开一些 API。)
我正在使用 sinon、QUnit 和 Pavlov。
I am trying to write test driven Javascript. Testing each function, I know, is crucial. But I came to a stumbling block, in that the plugin which I am writing needs to have some private functions. I cannot peek into how they are functioning. What would I need to do if I want to keep my code well tested without changing the structure of it too much? (I am ok with exposing some API, though within limits.)
I am using sinon, QUnit, and Pavlov.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您正在进行测试驱动开发(如标签所建议的),每行生产代码首先都会通过失败的测试用例来证明其合理性。
换句话说,生产代码的每一行的存在都经过隐式测试,因为如果没有它,某些测试必定会失败。话虽这么说,您可以放心地假设私有函数/lambda/闭包已经根据 TDD 的定义进行了测试。
如果您有一个私有函数并且想知道如何测试它,则意味着您一开始就没有进行 TDD - 现在您遇到了问题。
总而言之 - 永远不要在测试之前编写生产代码。如果遵循这条规则,每一行代码都会被测试,无论它有多深。
If you are doing test driven development (as suggested by the tags) each line of production code is first justified by failing test case.
In other words the existence of each and every line of your production code is implicitly tested because without it some test must have failed. That being said you can safely assume that private function/lambda/closure is already tested from the definition of TDD.
If you have a private function and you are wondering how to test it, it means you weren't doing TDD on the first place - and now you have a problem.
To sum up - never write production code before the test. If you follow this rule, every line of code is tested, no matter how deep it is.