title: Unit test a private method that uses request, pipe and stream using mocks
body: <p>I want to unit test the exported method in the code below. I want to mock the values in the private method to control the reject/resolves of the returned Promise. <code>client</code> is <a href="https://github.com/brianc/node-postgres" rel="noreferrer">node-postgres </a> object that is already connected to the database.</p>
  
  <p>I know I can use <a href="https://github.com/thlorenz/proxyquire" rel="noreferrer">proxyquire</a> to stub out required libraries but how can I mock the chained methods <code>.on('error', ...)</code>, <code>.pipe(stream)</code> and <code>.on('end', ...)</code> such that I can control the returned values.</p>
  
  <p><strong>Note</strong> the exported method shown is a simplification of the real one and exporting importDomain is not feasible.</p>
  
  <pre><code>const copyFrom = require('pg-copy-streams').from
  const request = require('request')
  const Promise = require('bluebird')
  
  // private
  function importDomain (client, domain) {
      return new Promise((resolve, reject) =&gt; {
      let stream = client.query(copyFrom(`COPY ${domain.table} FROM STDIN;`))
  
      let req = request(`${domain.url}`)
      req.on('error', reject)
      req.pipe(stream)
         .on('error', reject)
         .on('end', resolve)
    })
  }
  
  // public
  module.exports = (client) =&gt; {
    let domain = someFunctionReturningDomain()
    importDomain(client, domain)
  }
  </code></pre>