How can I use supertest lib using the same app instance in expressjs

114 Views Asked by At

I have the below code in my app.ts file. How can I export the app instance so that I can use it with superagent lib for my tests?

const port = 8080; 
const host = "0.0.0.0"; 
const init = async () => { 
    const app = express(); 
    const middlewareA = await middlewareA();
    app.use([middlewareA]); 
    app.use(routes); 
    app.listen(port, host, () => { 
        console.log(Working server on ${host}:${port}); 
    }); 
}; 
init();
1

There are 1 best solutions below

0
Heiko Theißen On

You cannot export the app asynchronously, but you can export the asynchronous init function and let it resolve to the app once it has started listening:

async function init() {
  const app = express(); 
  const middlewareA = await middlewareA();
  app.use([middlewareA]); 
  app.use(routes); 
  return new Promise(function(resolve, reject) {
    app.listen(port, host, () => { 
      console.log(Working server on ${host}:${port});
      resolve(app);
    });
  }); 
};

followed by module.exports = init; for Common JS modules or by export default init; for ES modules.

In order to use the init() function, you can then either import it and await its result in an ES module, or you can defer the init until the first request comes in that needs it. Both options are explained here.