node.jsexpressmocha.jschaichai-http

Error with running the Mocha test cases using chai-http for node services


I was trying to get a basic hang of writing the test cases using mocha and chai-http ,I had written the test case as below

let chai = require('chai');
let chaiHttp = require('chai-http');

const should = chai.should;
const expect = chai.expect;
const server = "http://127.0.0.1:3000"

chai.use(chaiHttp);

describe('Create Login and Register', () => {
    it('should login using credentials', (done) => {
        chai.request(server)
            .get('/register')
            .send()
            .then((res: any) => {
                res.should.have.status(200);
                done();
            }).catch((err: any) => { done(err) })
    })

})

and the service that i'm trying to test is as below

const express = require('express');
const app = express();

app.get('/register', function (req, res) {
    res.json({
        'state': true,
        'msg': 'Register endpoint',
        'data': {
            'username': 'Swarup',
            'email': 'abc@gmail.com',
            'password': 'P@1234',
            'fullName': 'Swarup Default'
        }
    });
});

app.listen(3000, () => { console.log('started') })

module.exports = app;

but when i run the test case i get an error as given below

1 failing

  1) Create Login and Register
       should login using credentials:
     Error: connect ECONNREFUSED 127.0.0.1:3000
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)

what is that i'm missing or doing wrong ?


Solution

  • You did not start the HTTP server. You should start the HTTP server in the before hook and teardown it in the after hook.

    Besides, you can have your module NOT execute the code in the conditional block at requiring by using require.main === module condition. Because we will require('./app') in our test file, we don't want to start the HTTP server at requiring.

    E.g.

    app.js:

    const express = require('express');
    const app = express();
    
    app.get('/register', function (req, res) {
      res.json({
        state: true,
        msg: 'Register endpoint',
        data: {
          username: 'Swarup',
          email: 'abc@gmail.com',
          password: 'P@1234',
          fullName: 'Swarup Default',
        },
      });
    });
    
    if (require.main === module) {
      app.listen(3000, () => {
        console.log('started');
      });
    }
    
    module.exports = app;
    

    app.test.js:

    let chai = require('chai');
    let chaiHttp = require('chai-http');
    let app = require('./app');
    
    const expect = chai.expect;
    const endpoint = 'http://127.0.0.1:3000';
    chai.use(chaiHttp);
    
    describe('Create Login and Register', () => {
      let server;
      before(() => {
        server = app.listen(3000, () => {
          console.log('started for testing');
        });
      });
      after(() => {
        server.close();
      });
      it('should login using credentials', (done) => {
        chai
          .request(endpoint)
          .get('/register')
          .send()
          .then((res) => {
            expect(res).to.have.status(200);
            done();
          })
          .catch((err) => {
            done(err);
          });
      });
    });
    

    test result:

      Create Login and Register
    started for testing
        ✓ should login using credentials
    
    
      1 passing (18ms)