Home > Enterprise >  how to import server app for chai request()?
how to import server app for chai request()?

Time:12-10

I want to run tests on my node express server however this application is starting the server like this:

createServer()
.then(server => {
    server.listen(PORT);
    Log.info(`Server started on http://localhost:${PORT}`);
})
.catch(err => {
    Log.error("Startup failure.", { error: err });
    process.exit(1);
});

and I know the chai.request() needs to have a parameter that is pointing toward the server app, how can I export/import this createServer() function and pass it in the request method of the chai object?

CodePudding user response:

You can use require.main to distinguish between your files being run directly by Node or imported as modules.

When a file is run directly from Node.js, require.main is set to its module. That means that it is possible to determine whether a file has been run directly by testing require.main === module.

E.g.

server.js:

const express = require('express');

const PORT = 3000;
async function createServer() {
  const app = express();
  app.get('/', (req, res) => {
    res.send('hello world');
  });
  return app;
}

if (require.main === module) {
  createServer()
    .then((server) => {
      server.listen(PORT);
      console.info(`Server started on http://localhost:${PORT}`);
    })
    .catch((err) => {
      console.error('Startup failure.', { error: err });
      process.exit(1);
    });
}

module.exports = { createServer };

When you import the createServer from the server.js file, the if statement block will not execute. Because you want to create the server instance in the test case.

server.test.js:

const { createServer } = require('./server');
const chai = require('chai');
const chaiHTTP = require('chai-http');
const { expect } = require('chai');
chai.use(chaiHTTP);

describe('70284767', () => {
  it('should pass', async () => {
    const server = await createServer();
    chai
      .request(server)
      .get('/')
      .end((err, res) => {
        expect(err).to.be.null;
        expect(res.text).to.be.equal('hello world');
      });
  });
});
  • Related