3

I am new to testing. I am using JEST to test my nodejs API's. When i am writing all the tests in one file its running properly without any error but when i am separating it its giving me port is already under use As for each file its running different node instance.

Both the files i am writing this to test

const supertest = require('supertest');
const app = require('../index');
describe('API Testing for APIs', () => {
  it('Healthcheck endpoint', async () => {
    const response = await supertest(app).get('/healthcheck');
    expect(response.status).toBe(200);
    expect(response.body.status).toBe('ok');
  });
});

How i can separate my test in different files to organise my tests in better way or is there anyway to organise test files.

PS - please suggest what are the best practises to write NodeJS api tests.

Cycl0n3
  • 611
  • 1
  • 6
  • 25

1 Answers1

2

When you use Express with Jest and Supertest, you need to separate in two different files your Express application definition and the application listen. Supertest doesn't run on any port. It simulates an HTTP request response to your Express application. It'll be something like this:

File: app.js

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

app.get('/healthcheck', (req, res) => {
    res.json({msg: 'Hello!'});
};

module.exports = app;

File: index.js

const app = require('./app');
app.listen(3000);

File: index.test.js

const request = require('supertest');
const app = require('./app');

test('Health check', async () => {
    const response = await request(app)
        .get('/healthcheck')
        .send()
        .expect(200);

   expect(response.body.msg).toBe('Hello!');
};
Andrés Muñoz
  • 559
  • 3
  • 8
  • my question is i need to separate two test files to make my tests more organised. If i am having all tests in one file its running fine – Cycl0n3 Jun 02 '20 at 09:06
  • You are having bussy port errors, so you need to separate your applicatoin server with your server definition and the listen method. When your test suite finally runs, without errors, a good practice is create one test file by each module. – Andrés Muñoz Jun 02 '20 at 09:10
  • Okay got it. is there anyway in jest it will run one by one file and after running one file it will close the server and open again when moving to next file – Cycl0n3 Jun 02 '20 at 09:16
  • 1
    As far as I know, no. In Jest, tests are parallelized by running them in their own processes to maximize performance. https://jestjs.io/en/ – Andrés Muñoz Jun 02 '20 at 09:22