Using td.replace() with external modules
See original GitHub issueBased on the node example I’ve tried to use td.replace() with a external module. The module I’m testing does something like this:
import elasticsearch from 'elasticsearch'
var client = new elasticsearch.Client({ ... })
client.search({ ... });
My test, currently using sinon, does something like this:
import sinon from 'sinon'
import elasticsearch from 'elasticsearch'
searchSpy = {
search: sinon.stub().returns(Promise.resolve({
hits: {
hits: [ ... ]
}
}))
}
sinon.stub(elasticsearch, 'Client').returns(searchSpy)
Stubbing only elasticsearch.Client is something I want to get rid of (to solve an unrelated problem). td.replace() seems like the right tool for that. So I tried something like this:
import elasticsearch from 'elasticsearch'
import td from 'testdouble'
searchSpy = {
search: sinon.stub().returns(Promise.resolve({
hits: {
hits: [ ... ]
}
}))
}
var es = td.replace('elasticsearch')
td.when(es.Client()).return(searchSpy)
That fails with TypeError: es.Client is not a function. td.when(es.Client) doesn’t work either.
Since there is no documentation for td.replace() and the example only imports internal module (with relative paths), I can’t tell if I’m doing it wrong (likely) or if this is just not supported (yet, also likely).
If the snippets above aren’t enough, I can also put together a sample that actually works.
Issue Analytics
- State:
- Created 8 years ago
- Comments:16 (6 by maintainers)

Top Related StackOverflow Question
Hey @jzaefferer and friends, I’ve changed my mind about this. Enough teams are using private modules at this point as a code organization strategy, that no one is benefited by the library preventing using
td.replacein this way, especially because it requires hardly any code changes on our part to support this. (Really it just requires resolving from the perspective of the current working directory).See #220
Yeah, we are open to it, but we still have the concerns we did at the outset–that giving folks a module replacement method would encourage replacing third party dependencies directly without wrapping them. At the same time that’s not always necessary (e.g. a separate module that you do control)
Anyway maybe someone has the time to look into adding this to quibble over the holiday.