i-like-robots / rewireify

Rewireify is a port of Rewire for Browserify that adds setter and getter methods to each module so that their behaviour can be modified for better unit testing.
https://www.npmjs.com/package/rewireify
Other
59 stars 10 forks source link

Rewire doesn't work when the module is a constructor function #23

Open jesantana opened 8 years ago

jesantana commented 8 years ago

Hi, First of all thanks for this great tool.

I have a constructor function declared in a module defined like this:

function f(){
    var privateFunction=function(){
        //do something
    }

    return {
        a:'some value'
    }
}
module.exports=f

and then I use it:

var obj=new f()

I want to use rewireify to test privateFunction, but the get method is only injected to f, no to its prototype, then I never have it in the created instances.

Will it make sense to have some kind of option indicating that the method should also be injected to the prototype, so the instances created with new also have the access functions?

i-like-robots commented 8 years ago

@jesantana at this time the tool only injects code into the module scope - there is no provision to analyse the syntax tree.

However I think your issue is quite straightforward to solve, by hoisting the private function out of the constructor and into module scope:

function privateFunction (){
  // do something
}

function f () {

  // call the function from this scope
  privateFunction.call(this)

  return {
    a: 'some value'
  }
}

module.exports = f