Skip to content

MongoDB Fixture ​

The mongoDbClient fixture provides a MongoDB client with full CRUD and aggregation capabilities. It uses the official MongoDB Node.js driver and manages connection lifecycle automatically.


What It Does ​

  • Connects to MongoDB (standalone, replica set, or Atlas via SRV)
  • Verifies connectivity with a ping command on setup
  • Provides typed CRUD operations: find, findOne, insertOne, insertMany, updateOne, updateMany, deleteOne, deleteMany
  • Supports aggregation pipelines
  • Closes the connection on teardown

Setup ​

Install ​

The driver is an optional peer dependency. Install it in your project:

bash
npm install --save-dev mongodb

Run it in a container ​

No MongoDB server to connect to? Set PW_MONGODB_CONTAINER=true (or container: true in config) and the fixture starts one with Testcontainers for the run, then removes it. Needs Docker and npm install --save-dev testcontainers. See Testcontainers.

Environment Variables ​

VariableRequiredDescription
PW_MONGODB_URINoFull MongoDB connection URI (overrides host/port/auth)
PW_MONGODB_HOSTNoMongoDB server host (default: localhost)
PW_MONGODB_PORTNoMongoDB server port (default: 27017)
PW_MONGODB_DATABASEYesDatabase name
PW_MONGODB_USERNAMENoAuthentication username
PW_MONGODB_PASSWORDNoAuthentication password

Configuration via environments.json ​

json
{
  "environments": {
    "dev": {
      "mongodb": {
        "host": "localhost",
        "port": 27017,
        "database": "myapp_test",
        "username": "admin",
        "password": "secret",
        "authSource": "admin",
        "connectionTimeout": 10000
      }
    },
    "prod": {
      "mongodb": {
        "uri": "mongodb+srv://user:[email protected]/myapp",
        "database": "myapp"
      }
    }
  }
}

Configuration via playwright.config.ts ​

typescript
import { defineConfig } from '@playwright/test';

export default defineConfig({
  projects: [
    {
      name: 'integration',
      testMatch: '**/integration/**/*.spec.ts',
      use: {
        mongodb: {
          host: 'localhost',
          port: 27017,
          database: 'myapp_test',
        },
      },
    },
  ],
});

Configuration Options ​

OptionTypeDefaultDescription
uristring—Full MongoDB connection URI (overrides host/port/auth)
hoststring'localhost'MongoDB server host
portnumber27017MongoDB server port
databasestring—Database name
usernamestring—Authentication username
passwordstring—Authentication password
authSourcestring'admin'Authentication source database
srvbooleanfalseUse mongodb+srv:// protocol
connectionTimeoutnumber10000Connection timeout in ms

Usage ​

Querying Documents ​

typescript
import { test, expect } from '@inluxc/propmaster';

test('find active users', async ({ mongoDbClient }) => {
  const users = await mongoDbClient.find<{ name: string; email: string }>(
    'users',
    { active: true },
    { limit: 10, sort: { name: 1 } }
  );

  expect(users).toBeDefined();
  expect(Array.isArray(users)).toBe(true);
});

test('find a single document', async ({ mongoDbClient }) => {
  const user = await mongoDbClient.findOne<{ name: string }>(
    'users',
    { email: '[email protected]' }
  );

  if (user) {
    expect(user).toHaveProperty('name');
  }
});

Inserting Documents ​

typescript
test('insert a document', async ({ mongoDbClient }) => {
  const result = await mongoDbClient.insertOne('users', {
    name: 'Alice',
    email: '[email protected]',
    active: true,
  });

  expect(result.acknowledged).toBe(true);
  expect(result.insertedId).toBeDefined();
});

test('insert multiple documents', async ({ mongoDbClient }) => {
  const result = await mongoDbClient.insertMany('users', [
    { name: 'User A', email: '[email protected]' },
    { name: 'User B', email: '[email protected]' },
  ]);

  expect(result.insertedCount).toBe(2);
});

Updating Documents ​

typescript
test('update a document', async ({ mongoDbClient }) => {
  const result = await mongoDbClient.updateOne(
    'users',
    { email: '[email protected]' },
    { $set: { active: false } }
  );

  expect(result.acknowledged).toBe(true);
  expect(result.matchedCount).toBeGreaterThanOrEqual(0);
});

Deleting Documents ​

typescript
test('delete a document', async ({ mongoDbClient }) => {
  const result = await mongoDbClient.deleteOne('users', {
    email: '[email protected]',
  });

  expect(result.acknowledged).toBe(true);
});

Aggregation Pipelines ​

typescript
test('run an aggregation', async ({ mongoDbClient }) => {
  const results = await mongoDbClient.aggregate<{ _id: boolean; count: number }>(
    'users',
    [
      { $group: { _id: '$active', count: { $sum: 1 } } },
      { $sort: { count: -1 } },
    ]
  );

  expect(results).toBeDefined();
  if (results.length > 0) {
    expect(results[0]).toHaveProperty('count');
  }
});

Find Options ​

OptionTypeDescription
limitnumberMaximum number of documents to return
skipnumberNumber of documents to skip
sortRecord<string, 1 | -1>Sort specification
projectionRecord<string, 0 | 1>Fields to include or exclude

Automatic Cleanup ​

Documents inserted with insertOne and insertMany are deleted by _id when the test ends, pass or fail. Pass { keep: true } as the last argument to leave them in place. Updates and deletes aren't undone. See Test Data and Automatic Cleanup.


Lifecycle ​

  1. Setup — Creates MongoClient, connects, verifies with a ping command
  2. Use — Provides mongoDbClient to the test
  3. Teardown — Closes the MongoClient connection

Error Handling ​

ErrorWhen
FixtureInitErrorConnection failure (includes host, port, database, timeout)
FixtureOperationErrorOperation failure (includes collection name and operation type)

Released under the MIT License.