'Testing express routes with MongoDB and Jest

I have a mongoDB database set up which is being accessed by calling the server it is running on (code below). I want to be able to test the different routes to check it is e.g. adding a record etc.

I've set up a jest test suite but am really struggling with how to set up the tests to use the routes but for the mock db I have set up?

If anyone could provide an example of how to fill in my records.test.js file to set up and be able to test the DB I would be very grateful!

in record.test.js

const db = require('./db')
beforeAll(async () => await db.connect())
afterEach(async () => await db.clearDB())
afterAll(async () => await db.closeDB())

describe('Adding a request', () => {
it('First Test', async done => {
    const newRecord = {
        holderAddress: "HOLDER123",
        otherAddress: "OTHER456",
        date: new Date(),
        data: "a1b2c3"
    }

})
})

In db.js (in test folder)

const chai = require('chai');
global.expect = chai.expect;
const mongoose = require('mongoose')
const { MongoMemoryServer } = require('mongodb-memory-server')

let mongoDB;

// Connect to db
module.exports.connect = async() => {
mongoDB = await MongoMemoryServer.create();
const uri = mongoDB.getUri();
const mongooseOpts = {
    maxPoolSize:50,
    wtimeoutMS:2500,
    useNewUrlParser:true
};
await mongoose.connect(uri, mongooseOpts);
}

// Disconnect from DB and close connection
module.exports.closeDB = async() => {
await mongoose.connection.dropDatabase();
await mongoose.connection.close();
await mongoDB.stop();
}

// Clear the DB and remove the data
module.exports.clearDB = async() => {
const collections = mongoose.connection.collections;
for (const key in collections) {
    const collection = collections[key];
    await collection.deleteMany();
}
}


Sources

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

Source: Stack Overflow

Solution Source