title: How to stub require() / expect calls to the "root" function of a module?
body: <p>Consider the following jasmine spec:</p>
  
  <pre><code>describe("something.act()", function() {
    it("calls some function of my module", function() {
      var mod = require('my_module');
      spyOn(mod, "someFunction");
      something.act();
      expect(mod.someFunction).toHaveBeenCalled();
    });
  });
  </code></pre>
  
  <p>This is working perfectly fine. Something like this makes it green:</p>
  
  <pre><code>something.act = function() { require('my_module').someFunction(); };
  </code></pre>
  
  <p>Now have a look at this one:</p>
  
  <pre><code>describe("something.act()", function() {
    it("calls the 'root' function of my module", function() {
      var mod = require('my_module');
      spyOn(mod); // jasmine needs a property name
                  // pointing to a function as param #2
                  // therefore, this call is not correct.
      something.act();
      expect(mod).toHaveBeenCalled(); // mod should be a spy
    });
  });
  </code></pre>
  
  <p>This is the code I'd like to test with this spec:</p>
  
  <pre><code>something.act = function() { require('my_module')(); };
  </code></pre>
  
  <p>This has bogged me down several times in the last few months. One theoretical solution would be to replace require() and return a spy created with createSpy(). BUT require() is an unstoppable beast: it is a different "copy" of the function in each and every source file/module. Stubbing it in the spec won't replace the real require() function in the "testee" source file.</p>
  
  <p>An alternative is to add some fake modules to the load path, but it looks too complicated to me.</p>
  
  <p>Any idea?</p>