Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Globally override a module that returns a function #56

Closed
TheSavior opened this issue Mar 25, 2015 · 6 comments
Closed

Globally override a module that returns a function #56

TheSavior opened this issue Mar 25, 2015 · 6 comments

Comments

@TheSavior
Copy link

I know that you can set '@global': true in the stubs for modules that are objects, but how do you do it for modules that return functions. For example:

// main.js
var Deep = require('./deep');

var instance = new Deep();
instance.run();

module.exports = instance;
// deep.js
var deepest = require('./deepest')('My Name');

function Deep() {
}

Deep.prototype = {
  run: function() {
    deepest.baz();
  }
};

module.exports = new Deep();
// deepest.js
function Deepest(name) {
  return {
    baz: function() {
      console.log(name);
    }
  };
}

module.exports = Deepest;

Deepest returns a function that I need to mock out, but since it is used inside of Deep, I have to use @global.

If deepest was exporting the inner object instead of the wrapping function, I could do this:

var main = proxyquire('./main.js', {
  './deepest': {
    '@global': true,
    'baz: function() {}
  }
}

But since deepest returns a function, my understanding is that I have to mock it like this:

var main = proxyquire('./main.js', {
  './deepest': function() {
    return {
      baz: function() {
        console.log('mocked');
      }
    }
  }
}

But I can no longer set '@global' on the mock object. Right? How should I handle this? This situation has arisen because of the api design of a third party module so I sadly can't really restructure these calls.

@bendrucker
Copy link
Collaborator

Sure you can! Just assign create a function assigned to a variable and then set deepest['@global'] = true.

var deepest = function () {}
deepest['@global'] = true

@TheSavior
Copy link
Author

Neat. Thanks!

@thlorenz
Copy link
Owner

Seems like we need to add these special cases to the docs and/or a wiki.

@bendrucker
Copy link
Collaborator

Sure. I think it merits its own section under API. Wikis don't actually get read. Agreed?

@thlorenz
Copy link
Owner

Agreed, currently we don't even have a wiki to speak of :)

@MarkHerhold
Copy link
Contributor

@bendrucker This '@global' = true implementation of yours is truly genius! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants