Search code examples
javascriptfunctionobjectnode.jsextend

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


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');


Solution

  • 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.