Test config with typescript and mongodb-Memory-Server
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();});