YSH
YSH

Reputation: 65

Multiple tests for RESTfull API with Chai and Moca - connecting to server

I'm trying to test my API and I'm having the following error:

Uncaught Error: listen EADDRINUSE: address already in use :::5000

this is my code:

test.ts

chai.use(chaiHttp)
describe('Persons', () => {
  describe('GET /person/', () => {
    it('check error path', (done) => {
      chai
        .request(startServer)
        .get("/persons/")
        .end((err, res) => {
          res.should.have.status(422);
        })
      done();
    });
  });
  // describe('GET /person/:firstName', () => {
    it('It should person by first name', (done) => {
      chai
      .request(startServer)
        .get("/persons/Ross")
        .end((err, res) => {
          res.should.have.status(200);
          res.body.should.be.a('string');
          // res.header["content-type"].should.contains('application/json');
        })
      done();
    });
  // });
});

server.ts

import express, { Application } from "express";
import personRouter from "./route/person.route";
import groupRouter from "./route/group.route";
import bodyParser from "body-parser";

const app: Application = express();
const PORT: Number | string = process.env.NODE_ENV || 5000;

app.use(bodyParser.json());

app.use('/person', personRouter)
app.use('/group', groupRouter)

export function startServer() {
    app.listen(PORT, () => {
        console.log(`Server started on http://localhost:${PORT}`);
    });
}

what am I doing wrong?

Upvotes: 0

Views: 59

Answers (1)

YSH
YSH

Reputation: 65

I ran the server from a diffrent place and then I did this:

describe('Persons', () => {
  const host = "http://localhost:5000/person/";

  describe('GET /person/', () => {
    it('check error path', (done) => {
      chai
        .request(host)
        .get("/persons/")
        .end((err, res) => {
          res.should.have.status(200);
        })
      done();
    });
  });

This way the server is not trying to start evry test.

Upvotes: 1

Related Questions