mingo-mongo-mock
v0.2.1
Published
MongoDB-driver-shaped in-memory mock collections powered by mingo.
Maintainers
Readme
mingo-mongo-mock
MongoDB-driver-shaped mock database for in-process JavaScript objects, powered by mingo.
Use this in tests when application code expects MongoDB-style collections, cursors, filters, updates, and aggregation pipelines, but you want the data to live in plain JavaScript objects in the same Node process.
Query, projection, aggregation, and update semantics are delegated to mingo where possible.
Install
pnpm add -D mingo-mongo-mockUsage
import { MockMongoDb } from 'mingo-mongo-mock'
const db = new MockMongoDb()
const users = db.collection('users')
await users.insertMany([
{ _id: 'u1', name: 'Alice', age: 30 },
{ _id: 'u2', name: 'Bob', age: 17 },
])
const adults = await users
.find({ age: { $gte: 18 } })
.sort({ name: 1 })
.toArray()
await users.updateOne(
{ _id: 'u1' },
{ $set: { active: true } },
)Documents inserted without _id get a MongoDB ObjectId:
const result = await users.insertOne({ name: 'Carol' })
console.log(result.insertedId)Aggregation $lookup resolves other named collections from the same mock DB:
const db = new MockMongoDb()
await db.collection('users').insertOne({ _id: 'u1', name: 'Alice' })
await db.collection('matches').insertOne({ _id: 'm1', userIds: ['u1'] })
const matches = await db.collection('matches').aggregate([
{
$lookup: {
from: 'users',
localField: 'userIds',
foreignField: '_id',
as: 'users',
},
},
]).toArray()Clear all mock data and indexes with the explicit test-helper method:
db.resetMock()API
new MockMongoDb()Database helpers
db.collection<T>(name)db.resetMock()db.getCollectionData<T>(name)db.setCollectionData<T>(name, documents)
getCollectionData and setCollectionData are test helpers for inspecting or directly replacing a collection's backing object array.
Supported collection methods
find(filter?, projectionOrOptions?)findOne(filter?, projectionOrOptions?)aggregate(pipeline?)insertOne(document)insertMany(documents, options?)updateOne(filter, update, options?)updateMany(filter, update, options?)replaceOne(filter, replacement, options?)findOneAndUpdate(filter, update, options?)deleteOne(filter)deleteMany(filter)countDocuments(filter?)distinct(path, filter?)createIndex(spec, options?)
createIndex supports unique indexes, including compound unique indexes, for duplicate-key checks in tests.
Supported find cursor methods
sort(sort)skip(count)limit(count)map(fn)toArray()next()hasNext()forEach(fn)close()- async iteration with
for await
Supported aggregation cursor methods
toArray()
Notes
- Mongo query, projection, aggregation, and update operator behavior comes from mingo.
- Known boundary:
[email protected]currently has a$renameupdate bug; a fix PR has been submitted upstream.
