@jperezmart/nest-mongodb-testing
v0.1.1
Published
Testing utilities for @jperezmart/nest-mongodb — spin up an ephemeral MongoDB without external infra.
Readme
@jperezmart/nest-mongodb-testing
Testing utilities for @jperezmart/nest-mongodb.
Spin up an ephemeral MongoDB with
mongodb-memory-server —
no external infra — and wire it into your Nest test module.
Install
pnpm add -D @jperezmart/nest-mongodb-testingMongoTestModule.forRoot(options?)
Boots an in-memory server and configures MongoModule.forRoot against it. The
server starts asynchronously, so await it in imports:
import {
MongoTestModule,
closeInMemoryMongo,
} from '@jperezmart/nest-mongodb-testing';
import { MongoModule } from '@jperezmart/nest-mongodb';
import { Test } from '@nestjs/testing';
let app: INestApplication;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [
await MongoTestModule.forRoot(), // { dbName?, replSet? }
MongoModule.forFeature(['cats']),
],
providers: [CatsService],
}).compile();
app = moduleRef.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
await closeInMemoryMongo();
});Pass { replSet: true } to start a single-node replica set when you need
transactions.
createTestCollection(name, options?)
For unit tests that don't boot Nest — connects a throwaway client and returns a collection plus its teardown:
import { createTestCollection } from '@jperezmart/nest-mongodb-testing';
const { collection, cleanup } = await createTestCollection<Cat>('cats');
await collection.insertOne({ name: 'Felix' });
// ...
await cleanup();closeInMemoryMongo()
Stops every in-memory server started by MongoTestModule. Call it in
afterAll.
License
MIT
