Skip to content Skip to sidebar Skip to footer

In Javascript/coffeescript How Can I Mock Out A Module's Public Variable In A Test?

I just learned about the module pattern. I've written some code that's gotten sufficiently complex that I want to test a feature. The problem is, I can't figure out how to mock o

Solution 1:

You want to use 'this' in that case,

doSomething = function() {
    returnalert(this.state);
};

In your code, 'state' refers to the variable (via closure) which is undefined. You then return an object containing a new 'state' property. You don't need the first 'state' variable, but only the property in your returned object.

'this' in doSomething refers to whatever object it is a part of. In test3, doSomething refers to the returned object with 'state' set to undefined. Once you set state in test3, the object's 'state' property is no longer the same as the private variable 'state' in test2-- it is overwritten in test3.

Essentially, you don't need the module pattern for the effect you desire, there's a much easier way:

root.test2 = {
    state: void0,
    doSomething: function() {
        returnalert(this.state);
    }
};

http://jsfiddle.net/rMJs5/

UPDATE:: I forget all about the Coffee part:

root = exports ? this
root.test2 = (->
  doSomething = -> alert this.state
  return {
    state: undefined
    doSomething: doSomething
  }
)()

Or, simply:

root = exports ? this
root.test2 = {
    state: undefineddoSomething: -> alert this.state
}

Post a Comment for "In Javascript/coffeescript How Can I Mock Out A Module's Public Variable In A Test?"