Jest testing without service connecting to DB

I am having issues with testing my nodejs app that has multiple connections to the DB.

I would like to run my test without creating any connections to the DB. However, since the individual connections are required in my model, it seems to be connecting to the DB even though it is not needed.

I am using jest with supertest for testing.


const mongoose = require('mongoose');
const { MONGO_URI1, MONGO_URI2 } = require('../config');

const db1Connection = mongoose.createConnection(MONGO_URI1, {
  useNewUrlParser: true,
  useUnifiedTopology: true,

const db2Connection = mongoose.createConnection(MONGO_URI2, {
  useNewUrlParser: true,
  useUnifiedTopology: true,

module.exports = {


const { Schema, model } = require('mongoose');
const { db1Connection } = require('../mongodbConnection');

const studentSchema = new Schema(
    studentId: { type: Number, required: true },
    email: { type: String, required: true },
    profileImage: { type: String, required: true },
    collection: 'students',
    timestamps: { updatedAt: 'lastModifiedTimeStamp' },

module.exports = db1Connection.model('StudentSchema', studentSchema);


const Student = require('../models/student.model');
const getUnitOffer = async (params) => {
  try {
    let unitOffer = await UnitOffer.findOne({ ...params })
    return unitOffer;
  } catch (error) {
    throw new Error('Cannot find Unit Offer');

So when I test the controller and mock the service, the error shows up that there is a need to connect to DB. However, I do not require that in my controller testing as I have mocked the service. So is there any way I can overcome this?

The tests works if i only make a single connection using mongoose.connect. However when I use the above code, it breaks the tests and asks for the env variables.

Read more here:

Content Attribution

This content was originally published by dontaskme123 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: