Reputation: 697
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.
Upvotes: 3
Views: 6982
Reputation: 579
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!');
};
Upvotes: 2