在javascript中测试私有函数 [英] Testing private functions in javascript

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

问题描述

我在Javascript中使用模块模式将我的公共接口与私有实现分开。为了简化我正在做的事情,我的代码生成了一个图表。该图表由多个部分(轴,标签,图,图例等)组成。我的代码如下所示:

I'm using the module pattern in Javascript to separate my public interface from the private implementation. To simplify what I'm doing, my code generates a chart. The chart consists of multiple parts (axises, labels, plot, legend, etc.) My code looks like:

var Graph = function() {
  var private_data;
  function draw_legend() { ... }
  function draw_plot() { ... }
  function helper_func() { ... }
  ...

  return {
    add_data: function(data) {
      private_data = data;
    },
    draw: function() {
      draw_legend()
      draw_plot()
    }
  }
}

有些人主张只测试你的课程的公共界面,这是有道理的,但我真的想进入一些测试分别测试每个组件。如果我搞砸了我的draw_legend()函数,我希望测试失败,而不是公共draw()函数的测试。我在这里走错路吗?

Some people advocate only testing the public interface of your classes, which makes sense, but I'd really like to get in some tests to test each of the components separately. If I screw up my draw_legend() function, I'd like that test to fail, not a test for the public draw() function. Am I on the wrong track here?

我可以将不同类中的每个组件分开,例如制作一个Legend类。但是,为有时只有5到10行代码创建一个类似乎很愚蠢,而且它会更加丑陋,因为我需要传递一堆私有状态。而且我无法测试我的助手功能。我还应该这样做吗?我应该吸吮它,只测试公共抽奖()吗?或者是否有其他解决方案?

I could separate each of the components in different classes, for example make a Legend class. But it seems silly to create a class for what's sometimes just 5-10 lines of code, and it would be uglier because I'd need to pass in a bunch of private state. And I wouldn't be able to test my helper functions. Should I do this anyway? Should I suck it up and only test the public draw()? Or is there some other solution?

推荐答案

无法从外部作用域访问内部函数(私有)。如果要测试内部函数,可以考虑添加公共方法以仅用于测试目的。如果您正在使用某种构建环境,例如ant,您可以预处理javascript文件以进行生产并删除这些测试函数。

There is no way to access inner functions (private) from an outer scope. If you want to test inner functions you might consider adding a public method for testing purposes only. If you are using some sort of a build environment, for example ant, you may pre-process the javascript file for production and remove those test functions.

实际上Javascript是一个面向对象的语言。它不是一个类型化的。

Actually Javascript is an Object oriented language. It's just not a statitcally typed one.

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

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