开发者

how to add function to an object in javascript that can access its variables

开发者 https://www.devze.com 2023-04-07 03:51 出处:网络
I am trying to do some javascript test driven development, and would like to replace a dao with a mock one.

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 insta开发者_运维百科nce 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');


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)

//something like this
function Dao(interface){
  this.dao = interface || new RealDao();
}

Otherwise, what you listed above is accurate. you just have to provide the setDao method as you indicated in your code.

0

精彩评论

暂无评论...
验证码 换一张
取 消