NestJS end to end testing with in-memory MongoDB example

Note Statistics

Note Statistics

  • Viewed 400 times
Sat, 05/08/2021 - 12:24

This example is based on the tutorials here. It provides a soution for end to end test with in memory MongoDB.

In this example have a test setup where

  • The CatModule is tested with an in-memory version of Mongoose.
  • A setup hook (beforeEach()) is used to populate the database and a teardown hook (afterEach()) is used to cleanup the database

Packages used

  • mongodb-memory-server for the in memory server.
  • fakingoose for generating mock data based on a mongoose schema.

The full example

import { Test, TestingModule } from '@nestjs/testing'
import { getModelToken, MongooseModule } from '@nestjs/mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { Cat, CatSchema, CatDocument } from './schemas/cat.schema';
import { CatModule } from './cat.module';
import request from 'supertest'
import { factory } from 'fakingoose'

describe('Cats controller', () => {
    let catModel;
    let app;
    const catFactory = factory<CatDocument>(CatDocument, {}).setGlobalObjectIdOptions({ tostring: false })
    beforeAll(async () => {
        const moduleFixture: TestingModule = await Test.createTestingModule({
            imports: [MongooseModule.forRootAsync({
                useFactory: async () => {
                    const mongod = new MongoMemoryServer();
                    const uri = await mongod.getUri();
                    return {
                        uri: uri
                    }
                }
            }), CatModule]
        })
            .compile()



        app = moduleFixture.createNestApplication()
        catModel = moduleFixture.get<Model<CatDocument>>(getModelToken(Cat.name))
        await app.init()
    })

    beforeEach(() => {
        // populate the DB with 1 cat using fakingoose
        const mockCat = catFactory.generate()
        return catModel.create(mockCat)
    })

    afterEach(() =>
        catModel.remove({})
    )

    it('GET /cats', () => {
        return request(app.getHttpServer())
            .get('/cats')
            .expect(200)
            .expect(res => {
                expect(res.body.length > 0).toBe(true)
            })
    })

    afterAll(() => {
        app.close()
    })
})

Related links

Authored by