title: Unable to test expressjs server
body: <p>I want to run some basic test on my expressjs server and immediately close it, but somehow I can't figure out how.
  I'm exporting the server as a promise.</p>
  <p>Here is my server file : index.js</p>
  <pre><code>const config = require(&quot;./config&quot;);
  const express = require(&quot;express&quot;);
  // Other imports
  const app = express();
  
  
  const ServerInfo = DatabaseService.init().then(
    () =&gt;
      new Promise((resolve, reject) =&gt; {
     
        // Load middlewares.
  
        // Load routes /api.
  
        let server = app.listen(config.port, config.host, () =&gt; {
         logger.log(
            &quot;info&quot;,
            `Server started on : http://${config.host}:${config.port}`
          );
          resolve(server);
        });
  
   
        });
      }),
    (err) =&gt; {
      console.log(&quot;error&quot;, &quot;Database is not ready!&quot;);
    }
  );
  
  module.exports = ServerInfo;
  </code></pre>
  <p>Here is my test file:</p>
  <pre><code>const chai = require(&quot;chai&quot;);
  const config = require(&quot;../../config&quot;);
  const server = require(&quot;../../index&quot;);
  
  const expect = chai.expect;
  
  describe(&quot;Server&quot;, () =&gt; {
    it(&quot;tests server starts on configured port.&quot;, function () {
      return server.then((serverObj) =&gt; {
        console.log(serverObj.address.port());
        expect(serverObj.address().port).to.equal(config.port);
      });
    });
  });
  
  </code></pre>
  <p>I intend to exit the program once the test is done.</p>
  <p><strong>Update</strong></p>
  <p>Finally I got it to work by updating the test file like so.</p>
  <pre><code>const chai = require(&quot;chai&quot;);
  const config = require(&quot;../../config&quot;);
  const server = require(&quot;../../index&quot;);
  
  const expect = chai.expect;
  describe(&quot;Server&quot;, () =&gt; {
    it(&quot;tests server starts on configured port &amp; host&quot;, function (done) {
      this.timeout(15000);
      server
        .then((serverObj) =&gt; {
          expect(serverObj.address().address).to.equal(config.host);
          expect(serverObj.address().port).to.equal(config.port);
          return serverObj;
        })
        .then((serverObj) =&gt; {
          serverObj.close(() =&gt; {
            done();
          });
        })
        .catch((err) =&gt; {
          done(err);
        });
    });
  });
  
  </code></pre>
  <p>Now the problem is that the test hangs without exiting after running all the test, I guess because the server doesn't close. Calling server.close() doesn't make any difference.</p>