Skip to content

Instantly share code, notes, and snippets.

@ageldama
Created April 20, 2024 04:33
Show Gist options
  • Save ageldama/5d70e1bbb08518b3fdff0bd21b4b414a to your computer and use it in GitHub Desktop.
Save ageldama/5d70e1bbb08518b3fdff0bd21b4b414a to your computer and use it in GitHub Desktop.
// https://dev.to/webeleon/unit-testing-nestjs-with-mongo-in-memory-54gd
// npm i --save-dev mongodb-memory-server
import { MongooseModule, MongooseModuleOptions } from '@nestjs/mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
let mongod: MongoMemoryServer;
export const rootMongooseTestModule = (options: MongooseModuleOptions = {}) => MongooseModule.forRootAsync({
useFactory: async () => {
mongod = new MongoMemoryServer();
const mongoUri = await mongod.getUri();
return {
uri: mongoUri,
...options,
}
},
});
export const closeInMongodConnection = async () => {
if (mongod) await mongod.stop();
}
import { Test, TestingModule } from '@nestjs/testing';
import { MongooseModule } from '@nestjs/mongoose';
import { SquidService } from './squid.service';
import { closeInMongodConnection, rootMongooseTestModule } from '../test-utils/mongo/MongooseTestModule';
import { SquidSchema } from './model/squid.schema';
describe('SquidService', () => {
let service: SquidService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [
rootMongooseTestModule(),
MongooseModule.forFeature([{ name: 'Squid', schema: SquidSchema }]),
],
providers: [SquidService],
}).compile();
service = module.get<SquidService>(SquidService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
/**
Write meaningful test
**/
afterAll(async () => {
await closeInMongodConnection();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment