Created
April 20, 2024 04:33
-
-
Save ageldama/5d70e1bbb08518b3fdff0bd21b4b414a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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