title: jest test emitting events for eventemitter objects (express)
body: <p>trying to get an inspiration from <a href="https://stackoverflow.com/questions/60435647/jest-test-emitting-events-for-eventemitter-objects-http/60446830?noredirect=1#comment106936387_60446830">jest test emitting events for eventemitter objects (http)</a> didn't solve my pain with <a href="https://github.com/expressjs/express" rel="nofollow noreferrer">express</a>.</p>
  
  <p>assume the following nodejs code</p>
  
  <pre class="lang-js prettyprint-override"><code>// server.js
  
  const express = require("express");
  const app = express();
  
  const server = app.listen(8080,'127.0.0.1')
    .on("error", err =&gt; {
      // ...
    });
  
  module.exports = server;
  </code></pre>
  
  <p>how to write a test using jest to emit the http "error" event (to cover the error event handler)?</p>
  
  <p>i tried:</p>
  
  <pre class="lang-js prettyprint-override"><code>// server.test.js
  
  it("should handle error", () =&gt; {
    jest.mock("express", () =&gt; () =&gt; ({
      listen: jest.fn().mockReturnThis(),
      on: jest.fn().mockImplementationOnce((event, handler) =&gt; {
        handler(new Error("network"));
      })
    }))
    const express = require("express");
    const app = express();
    const appListenSpy = jest.spyOn(app, "listen")
    require("./server");
    expect(appListenSpy).toBeCalledTimes(1);
    expect(app.listen).toBeCalledWith(8080,'127.0.0.1');
    expect(app.on).toBeCalledWith("error", expect.any(Function));
  });
  </code></pre>
  
  <p>but what i get when running the test</p>
  
  <pre class="lang-sh prettyprint-override"><code> ● server › should handle listen error
  
      expect(jest.fn()).toBeCalledTimes(expected)
  
      Expected number of calls: 1
      Received number of calls: 0
  
      &gt; 29 |     expect(appListenSpy).toBeCalledTimes(1);
  </code></pre>