title: sinonjs - stub a library referenced internally as a function using node modules (no require)
body: <p>I have an external library that is exported as a function, in the <a href="https://sinonjs.org/releases/v11.1.2/stubs/#var-stub--sinonstubobject-method" rel="nofollow noreferrer">Stub documentation</a> it only accepts an input with the first parameter as object and the second parameter as method , so how could I stub a library that is exported as a function in a Node ES Modules environment (without Commonjs)?</p>
  <p>(In my specific case, I had used a library that use the internet to work, and I wanted to test derivated functions without accessing the internet, so I want to stub the external function library)</p>
  <p>Attempts:</p>
  <ul>
  <li>I couldn't use solutions like <a href="https://www.npmjs.com/package/proxyquire" rel="nofollow noreferrer">proxyquire</a> as it is a solution based on <code>require</code> and <code>module cache deletion</code>, which are not supported within Node's ES modules.</li>
  <li>I don't want to use <a href="https://www.npmjs.com/package/proxyquire-universal" rel="nofollow noreferrer">proxyquire-universal</a> because it simulates the operation of <code>require</code> in normal ES, and it's just a function in the whole project that I wanted to test, I was looking for a simpler solution</li>
  <li>Changing the import mode doesn't work as it's not recompiled like in <code>babel</code>, so even if I import as <code>import * as obj from 'lib'</code> only the function name is changed</li>
  </ul>
  <p>I had this error environment with 3 files:</p>
  <blockquote>
  <p>An external library called &quot;sum&quot; for example, which I don't want to change, exported as follows:</p>
  <blockquote>
  <p><strong>External Library: externalSum.js</strong></p>
  <pre><code>module.exports = function sum(a, b){
    console.log(&quot;&gt;&gt;&gt;&gt;&gt; running without stub &lt;&lt;&lt;&lt;&lt;&quot;)
    return a + b
  }
  </code></pre>
  </blockquote>
  <p>This library used in the middle of a project file called mathProblems</p>
  <blockquote>
  <p><strong>Internal File: mathProblems.js</strong></p>
  <pre><code>import sum from 'externalSum'
  
  export function sumMore1(a) {
    return sum(a, 1);
  }
  </code></pre>
  </blockquote>
  <p>And I have a test file</p>
  <blockquote>
  <p><strong>Internal File: spec.js</strong></p>
  <pre><code>import sinon from 'sinon'
  import assert from 'assert'
  import sumObj from 'externalSum'
  import { sumMore1 } from '../mathProblems.js'
  
  describe('sumMore1 is working', () =&gt; {
    it('sumMore1 test', () =&gt; {
      const sum_stub = sinon.stub(sumObj) // NOT STUBBING
      sum_stub.withArgs(1, 1).returns(2) // NOT STUBBING
  
      const result = sumMore1(1)
      assert.strictEqual(result, 2)
    });
  });
  </code></pre>
  </blockquote>
  </blockquote>