Test config with typescript and mongodb-Memory-Server

Thilina Dilshan
Jan 18, 2022

First install these packages.

npm i --save-dev @types/jest jest @types/supertest supertest ts-jest mongodb-memory-server

Then write test script in package.json scripts section

"test": "jest --watchAll --no-cache"

Then write this script in outside the scripts section

"jest": {"preset": "ts-jest","testEnvironment": "node","setupFilesAfterEnv": ["./src/test/setup.ts"]},

create test folder and in there create setup.ts file

import { MongoMemoryServer } from "mongodb-memory-server";import mongoose from "mongoose";let mongo: any;
beforeAll(async () => {mongo = await MongoMemoryServer.create();const mongoUri = mongo.getUri();await mongoose.connect(mongoUri);});
beforeEach(async () => {jest.clearAllMocks();const collections = await mongoose.connection.db.collections();for (let collection of collections) {await collection.deleteMany({});}});
afterAll(async () => {await mongo.stop();await mongoose.connection.close();});

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Thilina Dilshan
Thilina Dilshan

Written by Thilina Dilshan

Software developer , love to learn

No responses yet

Write a response