如何向 JavaScript 中的对象添加可以访问其变量的函数
我正在尝试做一些 javascript 测试驱动开发,并且想用模拟的 dao 替换 dao。
假设我有一个对象 myObject,它有一个私有 var dao,我想为其创建一个 setter:
var dao = new RealDao();
function funcUsesDao() {
dao.doStuff();
}
然后在另一个文件中,我有一个该对象的实例的句柄,并且想要添加一个 setter,以便我可以执行以下操作:
var mockDao = {function doStuff() { /*mock code */}};
myObject.setDao(mockDao);
myObject.funcUsesDao(); should use mock dao
环境细节是这是node.js,我拥有句柄的对象是通过执行 var myObject = require('../myObject');
获得的
I am trying to do some javascript test driven development, and would like to replace a dao with a mock one.
Lets say I have an object myObject that has a private var dao that I would like to create a setter for:
var dao = new RealDao();
function funcUsesDao() {
dao.doStuff();
}
Then in another file I have a handle to an instance of this object and want to add a setter so I can do the following:
var mockDao = {function doStuff() { /*mock code */}};
myObject.setDao(mockDao);
myObject.funcUsesDao(); should use mock dao
Environment specifics are this is node.js and the object I have a handle to is obtained by doing var myObject = require('../myObject');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用该类的构造函数,将 dao 设置为 RealDao,然后在 setDao 中将该 dao 设置为新的 dao。或者,在构造函数中放置对 dao 的引用,并在 null 上将其分配给新的 RealDao()。 (至少,这是我对人们通常如何通过构造函数分配新接口进行测试的理解)
否则,您上面列出的内容是准确的。您只需提供代码中所示的 setDao 方法即可。
You would use a constructor for the class, setting the dao to RealDao and then in the setDao you would set that dao to the new dao. Alternately in the constructor you would put a reference to dao, and on null, assign it to a new RealDao(). (at least, that's been my understanding of how people generally assign new interfaces for testing .. via the constructor)
Otherwise, what you listed above is accurate. you just have to provide the setDao method as you indicated in your code.