title: jest: how to mock a dependency that listens to events?
body: <p>I came across a very complicated situation. <em>I'll try to keep it as concise as possible.</em></p>
  
  <p>So I have a code like this in <strong>myModule.js</strong>:</p>
  
  <pre><code>const lib = require('@third-party/lib');
  
  const myFunction = () =&gt; {
    const client = lib.createClient('foo');
    return new Promise((resolve, reject) =&gt; {
      client.on('error', (err) =&gt; reject(err));
      client.on('success', () =&gt; {
        client.as(param1).post(param2, param3, (err, data) =&gt; {
          if (err) reject(err);
  
          // Some important logical processing of data
          resolve(data);
        });
      });
    });
  }
  
  module.exports = { myFunction };
  </code></pre>
  
  <p>There are a few things I am able to mock, like: <code>createClient</code>. 
  What I am not able to mock is the event part <em>I don't even know how to do this.</em> And the <code>.as().post()</code> part.</p>
  
  <p>Here's how my <strong>jest test</strong> looks like:</p>
  
  <pre><code>const myModule = require('./myModule');
  const mockData = require('./mockData');
  
  describe('myFunction', () =&gt; {
  
    it('Should resolve promise when lib calls success event', async () =&gt; {
      try {
        const myData = await myModule.myFunction();
        expect(myData).toMatchObject(mockData.resolvedData);
      } catch (err) {
        expect(err).toBeNull();
      }
    })
  });
  </code></pre>
  
  <p>Any help, much Appreciated.</p>
  
  <p>I tried to find similar questions but at this point, my mind has just stopped working... 
  Please let me know if you need any more details. </p>