How to disconnect mongoose connection in jest

Viewed 15

I am doing unit tests for my express routes. I am getting this error from jest. My tests are passing but this error keeps on showing.

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  TLSWRAP

      4 |
      5 | module.exports = function () {
    > 6 |   mongoose.connect(connectionString, {
        |            ^
      7 |     useNewUrlParser: true,
      8 |     useUnifiedTopology: true,
      9 |   })

I have my DB setup in a different file name database.js

const mongoose = require('mongoose');

const connectionString = process.env.DATABASE_URL;

module.exports = function () {
  mongoose.connect(connectionString, {
    useNewUrlParser: true,
    useUnifiedTopology: true,   
  })
    .then(() => {
      console.log('Mongo Connection Open!');
    })
    .catch((err) => {
      console.log('Mongo Connection Error!', err);
    });
};

Have it in my app.js file as so

require("dotenv").config();
const express = require('express');
const app = express();
const path = require('path');
const cors = require("cors");

//==================================================
// Middleware
//==================================================
app.use(cors({
  origin: '*'
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '..', 'frontend', 'build')));

//==================================================
// DATABASE
//==================================================
const dbSetup = require('./src/databases/database');
dbSetup();

My test file looks like this

const request = require('supertest')
const app = require('../../app')
const mongoose = require('mongoose')
const User = require('../../src/models/user')


beforeAll(async () => {
    await User.findOneAndDelete({ email: 'testemail@gmail.com' })
})

//close the connection to the database
afterAll(() => mongoose.connection.close()) <--- THIS IS NOT WORKING

describe("Test user routes", () => {


  //sign up a new user
  it("should sign up a new user", async () => {
    const res = await request(app)
      .post('/users/signup')
      .send({
        email: 'testemail@gmail.com',
        password: 'testpassword'
      })
      .set('Accept', 'application/json')
      .expect(200)
})

I tried the afterAll hook to disconnect/close the connection but that isn't working. I am stuck, anyone knows a solution to this problem?

0 Answers
Related