'Connection Not established in Mocha to MongoDB Atlas

When starting my application it connects to MongoDB Atlas as logged, however, when running mocha tests it does not even try to connect to the DB.

here is my server.js file

require('dotenv').config()

const express = require('express');

const connectDB = require('./DB/connection')


const app = express();

app.use(express.json())


const PORT = process.env.PORT


connectDB();
app.listen(PORT, () => console.log(`Server started at ${PORT}`))

and this is the connection..js file

const mongoose = require('mongoose');
const URI = `mongodb+srv://${process.env.DB_USERNAME}:${process.env.DB_PASSWORD}@betacluster.7jf4v.mongodb.net/servicenowclone?retryWrites=true&w=majority`

const connectDB = async () => {
  try {
    mongoose.connect(URI, {
      useUnifiedTopology: true,
      useNewUrlParser: true
    });

    mongoose.connection.once('open',function() {
      console.log('connection established');
    }).on('error',() => console.log('gi atay way connection sa database man'))

  } catch (err) {
    console.log(err)
  }

}

which logs

Server started at 3000
connection established

so I know it connects to the DB successfully, however when creating tests using mocha, it doesn't even try to connect to the DB, here is the complete test file.

const mocha = require('mocha');
const assert = require('assert');
const ticketInstance = require('../models/ticket')

//describe tests
describe('saving a ticket', function () {


  it('create ticket', async function (done) {
    const newTicket = new ticketInstance({
      number: 1,
      type: 'Request',
      customer: 'Carlo Principe',
      description: 'first ticket created from a test',
      subject:'test subject'
    })

    newTicket.save().then(function (){
      assert(newTicket.isNew === false);
      done()
    })
    });
  })

Am I missing something, it logs timeout exceeded and does not show the connection established console.log I created in connection.js

Thanks!



Solution 1:[1]

The best way is mocha --delayed switch. mocha doc says

If you need to perform asynchronous operations before any of your suites are run (e.g., for dynamically generating tests), you may delay the root suite. Run mocha with the --delay flag.

For example, use mocha in this way mocha --recursive --exit --delay --ui tdd tests.js and --delayed enable you to trigger running the root suite via calling run() explicitly.

const fn = async x => {
  return new Promise(resolve => {
    setTimeout(resolve, 1500, 2 * x);
  });
};

(async function() {
  const z = await fn(3);

  suite("won't run until run() executes", () => {})

  run();
})();

For more information, please read https://mochajs.org/#delayed-root-suite.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1