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

td.replace () breaks the cache in require #244

Closed
jlobo opened this issue May 10, 2017 · 1 comment
Closed

td.replace () breaks the cache in require #244

jlobo opened this issue May 10, 2017 · 1 comment

Comments

@jlobo
Copy link

jlobo commented May 10, 2017

I have the following code

brake.js

console.log('new instance of brake')
module.exports = () => {}

car.js

console.log('new instance of car')
var brake = require('./brake')

module.exports = {
  slowDown: () => brake(10),
  stop: () => {}
}

test.js

const td = require('testdouble')
const brake = td.replace('./brake')
let subject = require('./car')
subject = require('./car')
subject = require('./car')

And the result is

$ npm run test
new instance of brake
new instance of car
new instance of car
new instance of car

As you can see the car is no longer being cached and therefore creates an object every time require is called.

In my personal test I need to have only one car object because another js require it, but when I change the behavior with td.replace(car, 'stop') nothing happen. The other js call require('./car') and then a new object is created.

@searls
Copy link
Member

searls commented May 10, 2017

Yes, this is by design. (Read quibble's source for more details). There's no sensible other way to fake require without bypassing the module cache. If we allowed tainted subjects (and because they have been handed fake things, they are tainted) into the module cache, we'd be asking for trouble in the event that anything else required them asynchronously or later on, or if multiple fake configurations were made via different calls to td.replace.

After you call td.reset(), the cache will be restored such that if a real car is already cached, that singleton will continue to be returned and it it's not already cached, the real one will be loaded and then cached as it would normally.

@searls searls closed this as completed May 10, 2017
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