title: Sinon - Stub module function and test it without dependency injection
body: <p>I have a proxy module, which forwards function calls to services. I want to test if the service function is called, when a function in this proxy module is called.</p>
  
  <p>Here is the proxy module:</p>
  
  <pre><code>const payService = require('../services/pay')
  const walletService = require('../services/wallet')
  
  const entity = {
      chargeCard: payService.payByCardToken,
      // ... some other fn
  }
  
  module.exports = entity
  </code></pre>
  
  <p>Based on <a href="https://railsware.com/blog/2017/01/10/mocking-es6-module-import-without-dependency-injection/" rel="noreferrer" title="this example">this example</a> and <a href="https://stackoverflow.com/questions/27462799/sinon-how-to-stub-nested-function" title="this response">this response</a>, I tried to stub the required module 'payService':</p>
  
  <pre><code>const expect = require('expect.js')
  const sinon = require('sinon') 
  const entity = require('../entity')
  const payService = require('../../services/pay')
  
  describe('Payment entity,', () =&gt; {
  
      it('should proxy functions to each service', () =&gt; {
  
          const stub = sinon.stub(payService, 'payByCardToken')
          entity.chargeCard()
          expect(payService.payByCardToken.called).to.be.ok()
  
      })
  })
  </code></pre>
  
  <p>But the test fails with:</p>
  
  <pre><code>  0 passing (19ms)
    1 failing
  
    1) Payment entity,
         should proxy functions to each service:
       Error: expected false to be truthy
        at Assertion.assert (node_modules/expect.js/index.js:96:13)
        at Assertion.ok (node_modules/expect.js/index.js:115:10)
        at Function.ok (node_modules/expect.js/index.js:499:17)
        at Context.it (payments/test/entity.js:14:56)
  </code></pre>
  
  <p>And that's because payService module isn't really stubbed. I know if I add payService as a property of entity and wrap everything with a function, the test will pass:</p>
  
  <pre><code>// entity
  const entity = () =&gt; {
      return {
          payService,
          chargeCard: payService.payByCardToken,
          // .. some other fn
      }
  }
  
  // test
  const stub = sinon.stub(payService, 'payByCardToken')
  entity().chargeCard()
  expect(payService.payByCardToken.called).to.be.ok()
  
  // test output
  Payment entity,
    ✓ should proxy functions to each service
  
  1 passing (8ms)
  </code></pre>
  
  <p>But that's code added only for testing puposes. Is there a way to a way to stub module functions without dependency injection and workarounds? </p>