title: How to stub constant functions when using ES Modules with sinon.js?
body: <p>With ES Modules, we define some exported functions as <code>const</code> and it is often a standard practice. However, during unit testing, these const functions can't be stubbed out which seems problematic from a unit testing perspective. For example,</p>
  
  <pre><code>import * as fs from 'fs';
  
  import { bindNodeCallback } from 'rxjs';
  import { map } from 'rxjs/operators';
  
  // readFile :: string, string =&gt; Observable&lt;string&gt;
  export const readFile$ = bindNodeCallback(fs.readFile);
  
  // readJson :: string =&gt; Observable&lt;any&gt;
  export function readJson(fileName) {
      return readFile$(fileName, 'utf-8')
          .pipe(map((rawFile) =&gt; JSON.parse(rawFile)));
  }
  </code></pre>
  
  <p>Now to unit test readJson, I would typically want to stub <code>readFile$</code> function. Unfortunately, following Sinon code doesn't work:</p>
  
  <pre><code>// Setup data - stubs / mocks
  const stub = sinon.stub(myFs, 'readFile$').returns(json$);
  </code></pre>
  
  <p>Since Sinon is simply changing reference <code>myFs.readFile$</code>, original <code>const</code> still points to the original function which is in turn called by <code>readJson</code> function.</p>
  
  <p><strong>Any suggestion - how can I really stub/mock constant function within the same module?</strong></p>