title: How to mock pg Pool with Sinon
body: <p>In a previous project I mocked the <a href="https://www.npmjs.com/package/mysql" rel="nofollow noreferrer">mysql library</a> with <a href="https://sinonjs.org/" rel="nofollow noreferrer">Sinon</a>.  I did this like so:</p>
  
  <p><code>X.js</code>:</p>
  
  <pre><code>const con = mysql.createPool(config.mysql);
  ...
  </code></pre>
  
  <p><code>Some other place in the project</code>:</p>
  
  <pre><code>const rows = await con.query(query, inserts);
  ...
  </code></pre>
  
  <p><code>X.test.js</code>:</p>
  
  <pre><code>const sinon = require('sinon');
  const mockMysql = sinon.mock(require('mysql'));
  ...
  
  mockMysql.expects('createPool').returns({
          query: () =&gt; {
              // Handles the query...
          },
  ...
  </code></pre>
  
  <p>It worked perfectly.</p>
  
  <p>In another project I am trying to mock <a href="https://www.npmjs.com/package/pg" rel="nofollow noreferrer">pg</a>, again with Sinon.  </p>
  
  <p><code>pool.js</code>:</p>
  
  <pre><code>const { Pool } = require('pg');
  const config = require('@blabla/config');
  const pool = new Pool(config.get('database'));
  
  module.exports = pool;
  </code></pre>
  
  <p><code>Some other place in the project</code>:</p>
  
  <pre><code>const con = await pool.connect();
  const result = await con.query(...
  </code></pre>
  
  <p><code>Y.test.js</code>:</p>
  
  <pre><code>???
  </code></pre>
  
  <p>I can't understand how to mock <code>connect().query()</code>.  None of the following approaches work:</p>
  
  <p>1:</p>
  
  <pre><code>const { Pool } = require('pg');
  const config = require('@blabla/config');
  
  const mockPool = sinon.mock(new Pool(config.get('database')));
  ...
  mockPool.expects('connect').returns({
    query: () =&gt; {
      console.log('query here');
    },
  });
  </code></pre>
  
  <p>1 results in no error but the real db connection is used.</p>
  
  <p>2:</p>
  
  <pre><code>const { Pool } = sinon.mock(require('pg'));
  const config = require('@blabla/config');
  
  const pool = new Pool(config.get('database'));
  
  pool.expects('connect').returns({
    query: () =&gt; {
      console.log('query here');
    },
  }); 
  </code></pre>
  
  <p>2 => <code>TypeError: Pool is not a constructor</code></p>
  
  <p>3:</p>
  
  <pre><code>const { Pool } = sinon.mock(require('pg'));
  const config = require('@blabla/config');
  
  const pool = sinon.createStubInstance(Pool);
  pool.connect.returns({
    query: () =&gt; {
      console.log('query here');
    },
  });
  </code></pre>
  
  <p>3 => <code>TypeError: The constructor should be a function.</code></p>
  
  <p>Can anybody point me in the right direction with how to mock my PostgreSQL connection?</p>