title: How can I test express server with supertest in next.js?
body: <p>I have built my portfolio webpage with next.js now I need to test it. to test the express server I use supertest. But the problem is I need to refactor express to use it. Because supertest need to access to app() before listening. </p>
  
  <p>I started the way how I used to implement in node.js app. Put the express code in app.js and call it in index.js.</p>
  
  <pre><code>const express = require("express");
  const server = express();
  const authService = require("./services/auth");
  const bodyParser = require("body-parser");
  //put all the middlewares here
  
  module.exports = server;
  </code></pre>
  
  <p>and then in index.js</p>
  
  <pre><code>const server = require("express")();
  // const { parse } = require("url");
  const next = require("next");
  const routes = require("../routes");
  
  const path = require("path");
  require("./mongodb");
  
  const dev = process.env.NODE_ENV !== "production";
  const app = next({ dev });
  // const handle = app.getRequestHandler(); //this is built in next route handler
  const handle = routes.getRequestHandler(app);
  
  
  app
    .prepare()
    .then(() =&gt; {
       const server = require("./app");
       //I required this outside too but it did not solve the issue
  
  
      server.listen(3000, (err) =&gt; {
        if (err) throw err;
        console.log("&gt; Ready on http://localhost:3000");
      });
    })
    .catch((ex) =&gt; {
      console.error(ex.stack);
      process.exit(1);
    });
  </code></pre>
  
  <p>with this set up, express is listening, I am able connect to mongodb, during the start up there is no issue. </p>
  
  <p>When i request to localhost:3000, there is no response from localhost, it is spinning till timeout</p>