I can't figure out what's wrong with my code... I'm testing my API endpoint with the following test but it timeout.
When I test it with postman or curl it works perfectly it only timeout when it is tested with mocha and chai unit tests.
Test:
describe('test', () => {
it('test', (done) => {
chai.request(app)
.get('/user')
.end((err, res) => {
res.should.have.status(200);
done();
})
})
});
Endpoint:
const express = require('express');
const router = express.Router();
const database = require('../database/connection');
router.get('/', async (req, res) => {
const collection = database.collection('user');
const users = await collection.find().toArray();
res.status(200).send(users);
});
module.exports = router;
connection.js
const config = require('../config');
const mongoose = require('mongoose');
mongoose.connect(
'mongodb://' + config.database.username + ':' + config.database.password + '@' + config.database.host + ':' + config.database.port + '/' + config.database.database,
{ useNewUrlParser: true, useUnifiedTopology: true }
);
let database = mongoose.connection;
database.on('error', () => {
console.error.bind(console, 'Failed to connect to mongo database');
process.exit(1);
});
database.once('open', () => {
if (config.name !== 'tests') {
console.log('Connected to mongo database');
}
});
module.exports = database;