title: When using rewire and sinon fakeTimer, order matters?
body: <p>While testing a setup with a timed interval, I came across this problem.</p>
  
  <p>First of all, I am using <a href="http://sinonjs.org/docs/#clock" rel="nofollow">sinon's fakeTimers</a> to create the right timed environment. <a href="https://github.com/jhnns/rewire" rel="nofollow">rewire</a> is used as dependency injection library. </p>
  
  <p>The problem is, that sometimes applying the fake timer seems to fail when rewire is involved while in some other instances it's perfectly working.</p>
  
  <p>Please check out this setup:</p>
  
  <p><em>test.js</em></p>
  
  <pre><code>'use strict';
  
  require('should');
  var sinon = require('sinon');
  var rewire = require('rewire');
  
  // this sample will not fall under the fake timer
  var SampleGlobal = rewire('./testmodule');
  
  describe('Sinon fake timer with rewirejs', function() {
  
      var clock;
  
      before(function() {
          clock = sinon.useFakeTimers();
      });
  
      after(function() {
          clock.restore();
      });
  
      it('work for locally rewired module', function() {
  
          var spy = sinon.spy();
  
          // locally inject-required module
          var Sample = rewire('./testmodule');
  
          new Sample().on('test', spy);
  
          spy.callCount.should.equal(0);
  
          clock.tick(5000);
  
          spy.callCount.should.equal(1);
  
      });
  
      it('break when rewired from global scope', function() {
  
          var spy = sinon.spy();
  
          // the module is globally inject-required
          new SampleGlobal().on('test', spy);
  
          spy.callCount.should.equal(0);
  
          clock.tick(5000);
  
          spy.callCount.should.equal(1);
  
      });
  
  });
  </code></pre>
  
  <p>Now to include a second module with the interval:</p>
  
  <p><em>testmodule.js</em></p>
  
  <pre><code>'use strict';
  
  var EventEmitter = require('events').EventEmitter;
  var util = require('util');
  
  function Sample() {
  
      this.h = setInterval(this.emit.bind(this, 'test'), 5000);
  
  }
  
  util.inherits(Sample, EventEmitter);
  
  module.exports = Sample;
  </code></pre>
  
  <p>Now, as you can see, the second test fails. This is the test that is using the module as it's required on top of the script (aka on the global scope). So I suspect it's because how rewire works and due to when the fakeTimers get installed.</p>
  
  <p>Can anyone explain this in detail? Is there a way I can use inject-required modules with rewire on the global scope or do I always have to rewire them at the lower levels?</p>