Skip to main content
Version: v4.x.x

Database Testing with Poku and MongoDB

End-to-end example of testing a MongoDB database with Poku and the official mongodb driver, from installing the driver to spinning the database up with Docker Compose.

Open the connection in an outer describe, put every assertion inside its own it, and close the connection at the end of that same describe, so cleanup always runs regardless of what an individual assertion does. MongoDB has no temporary collection, so the document persists in a shared collection, and the suite runs with sequential to keep the data deterministic. The container lifecycle lives in a poku.config.js anonymous plugin that uses @pokujs/docker to run setup before the suite and teardown after it, so the suite runs with a plain npm test.

Install​

npm i mongodb
npm i -D poku tsx @pokujs/docker

Configure the credentials​

.env.test:

DB_USER=root
DB_PASSWORD=secret
DB_PORT=27017
DB_NAME=app
DATABASE_URL="mongodb://${DB_USER}:${DB_PASSWORD}@localhost:${DB_PORT}/${DB_NAME}?authSource=admin"

.gitignore:

.env.test

Start the database​

docker-compose.yml reads the same .env.test to configure the container:

services:
mongodb:
image: mongo:8
environment:
MONGO_INITDB_ROOT_USERNAME: ${DB_USER}
MONGO_INITDB_ROOT_PASSWORD: ${DB_PASSWORD}
ports:
- '${DB_PORT}:27017'
healthcheck:
test: ['CMD', 'mongosh', '--eval', "db.adminCommand('ping')"]
interval: 5s
timeout: 5s
retries: 10
start_period: 30s

db-ready:
image: busybox
command: ['tail', '-f', '/dev/null']
depends_on:
mongodb:
condition: service_healthy

Connect​

db.ts reads every access from process.env:

import { MongoClient } from 'mongodb';

export const connect = () => MongoClient.connect(process.env.DATABASE_URL!);

Write the test​

users.test.ts:

import { describe, it, assert } from 'poku';
import { connect } from './db.js';

interface User {
id: number;
name: string;
}

await describe('Users collection', async () => {
const client = await connect();
const users = client.db(process.env.DB_NAME).collection<User>('users');

await describe('Seed', async () => {
await users.insertOne({ id: 1, name: 'Poku' });
});

await it('reads the inserted user', async () => {
const user = await users.findOne({ id: 1 });

assert.strictEqual(user?.name, 'Poku', 'The inserted user is returned');
});

await client.close();
});

Configure Poku​

poku.config.js:

import { defineConfig } from 'poku';
import { docker } from '@pokujs/docker';

const compose = docker.compose({ envFile: '.env.test' });

export default defineConfig({
envFile: '.env.test',
sequential: true,
plugins: [
{
setup: () => compose.up(),
teardown: () => compose.down(),
},
],
});
tip

Configuring Poku is optional: you can orchestrate your containers however you prefer and run Poku as poku --envFile='.env.test' --sequential, for example. In that case, @pokujs/docker is not needed.

Run​

Add the test script to package.json:

{
"scripts": {
"test": "poku"
}
}

Then run it:

npm test