I'm developing a REST API for an assignment and currently I have few endpoints and I'm writing test cases on the go. Strange thing happen when I make a test to check if the database is connected correctly. I have several GET
and POST
methods. The POST
always passes if I pass valid data. So I moved forward making a test to check the database connection.
When I place the POST
method before GET
, the test "API connects with mongodb" passes.
describe('Admin adds a new user', function () {
it('Request to add a user without authorization', function (done) {
request(app)
.post('/api/admin/user/add')
.send({
username: "Padmal1",
password: "abc123",
isAdmin: false
})
.expect(400, done);
});
});
describe('API connects with mongodb', function () {
it('Successful database connection', function (done) {
request(app)
.get('/api')
.expect(200, done);
});
});
But when I put GET
before POST
, the test "API connects with mongodb" fails saying socket hang up
describe('API connects with mongodb', function () {
it('Successful database connection', function (done) {
request(app)
.get('/api')
.expect(200, done);
});
});
describe('Admin adds a new user', function () {
it('Request to add a user without authorization', function (done) {
request(app)
.post('/api/admin/user/add')
.send({
username: "Padmal1",
password: "abc123",
isAdmin: false
})
.expect(400, done);
});
});
Following are the methods used in this API;
const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const MongoClient = require('mongodb').MongoClient
const ObjectID = require('mongodb').ObjectID;
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
var db = undefined;
MongoClient.connect('mongodb://localhost:27017/posdb',
{ useNewUrlParser: true })
.then(client => {
db = client.db('posdb');
db.collection('col_users').createIndex({ "username": 1 }, { unique: true });
})
.catch(res => {
console.log(res.name);
});
app.get('/api', (req, res) => {
// Test endpoint to test database connection
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
"status": "API is up and running with a Mongo DB @ " +
db.serverConfig.s.host + ':' + db.serverConfig.s.port
}));
});
app.post('/api/admin/user/add', (req, res) => {
try {
if (req.headers.authorization) {
// TODO: Verify authentication
try {
if (req.body.username) {
db.collection('col_users').insertOne(req.body, function (err, r) {
if (err) {
res.writeHead(403, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: "Duplicate username ..." }));
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ _id: r.insertedId }));
}
});
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: "No user to add ..." }));
}
} catch (e) {
if (e instanceof SyntaxError) {
res.writeHead(503, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: "JSON format seems wrong ..." }));
}
}
} else {
throw new ReferenceError;
}
} catch (e) {
if (e instanceof TypeError) {
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: "Database seems out of our hands ..." }));
} else if (e instanceof ReferenceError) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: "Invalid user request ..." }));
}
}
});
I did some research on this issue and couldn't get any idea related to it. I'm very new to NodeJS development though. When I try the link in a browser, it seems working fine giving expected results.
I also tried adding connection:keep-alive to headers but didn't work. Only this works is placing GET
test after POST
test. What could be the issue? Thanks for any tips :)