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

stubbing module exports with closures #1248

Closed
markbrown4 opened this issue Jan 25, 2017 · 2 comments
Closed

stubbing module exports with closures #1248

markbrown4 opened this issue Jan 25, 2017 · 2 comments

Comments

@markbrown4
Copy link

markbrown4 commented Jan 25, 2017

I can't seem to find a way to gracefully stub the exported a() here:

// lib.js
const a = () => {}
const b = () => {
  a()
}

module.exports = { a, b }
// test.js
const assert = require('assert')
const sinon = require('sinon')

const lib = require('./lib')
const stub = sinon.stub(lib, 'a')
lib.b()
assert(stub.called)

I'm guessing this fails because b has it's own copy of a.
I can do something like this which makes the test pass but it makes me want to take a shower.

const a = () => {}
const b = () => {
  toExport.a()
}

const toExport = { a, b }

module.exports = toExport

Any other options?

Cheers,

@fatso83
Copy link
Contributor

fatso83 commented Jan 26, 2017

You need to have a way of injecting your stub to do this cleanly. Something like

...
module.exports = { 
    a, 
    b, 
    __injectA = function(fn){ a = fn; },
    __injectB = function(fn){ b = fn; } 
}

Of course, since you are changing the internals of the module it will affect everything else using this module. If you want to do this without altering some kind of global state, you will need to create those functions in a closure created by some exported init function.

@fatso83 fatso83 closed this as completed Jan 26, 2017
@markbrown4
Copy link
Author

markbrown4 commented Jan 26, 2017 via email

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

2 participants