title: Pattern for unit testing stateful RequireJS modules
body: <p>Say I have a RequireJS module, and there is only ever one instance in my app (say it does something asynchronous and has callbacks passed to it):</p>
  
  
  
  <pre class="lang-javascript prettyprint-override"><code>// modules/myModule
  define(function(){
      var module = function(){
          var self = this;
          self.runSomething(){
              console.log("hello world");
          };
      };
  
      return new module();
  });
  </code></pre>
  
  <p>and I want to unit test an instance of this module, I have found myself constructing the module this way instead:</p>
  
  <pre class="lang-javascript prettyprint-override"><code>// modules/myModule
  define(function(){
      return function(){
          var self = this;
          self.runRouting(){
              console.log("hello world");
          };
      };
  });
  
  // modules/myModuleInstance
  define(["modules/myModule"], function(myModule){
      return new myModule();
  });
  </code></pre>
  
  <p>This provides me something with no state attached which I can then poke from my unit tests, so in my unit tests I never reference <code>modules/myModuleInstance</code>, only <code>modules/myModule</code>, which I construct each time for each test.  The app then references <code>modules/myModuleInstance</code>.</p>
  
  <p>This feels like an anti-pattern.  I hate having the extra "module instance" part in there.  I know about setup and teardown methods in unit tests, and <em>could</em> maintain the instance this way, but having witnessed what can happen with C# when attempting to unit test massive singletons, fiddling with state between unit tests is something I really want to avoid, especially with a dynamic language.</p>
  
  <p>What do people normally do in this case?</p>