Database testing is an important part of building reliable Node.js applications. Unit tests can verify individual functions, but they cannot always identify problems that occur when application code communicates with an actual database.
A query may work with mocked data but fail against a real database because of incorrect SQL syntax, missing constraints, transaction behavior, data type differences, or unexpected database responses. These problems often appear only after an application reaches an integration or production environment.
One way to improve database testing is to run tests against a temporary real database. Instead of connecting to a shared development database or mocking every database operation, the test suite starts an isolated database, executes the tests, and removes the database environment afterward.
Tools such as Testcontainers make this approach practical for Node.js applications. They allow tests to start database instances in containers and connect to them using normal database drivers.
In this article, we will explore why real database testing matters, how to start a temporary PostgreSQL database, and how to write integration tests using Node.js built-in test tools. We will also discuss migrations, test isolation, cleanup, performance, and common mistakes.
Why Mocking a Database Is Not Always Enough
Mocking is useful when testing application logic that depends on a database. It allows developers to control the returned data without starting a database server.
For example, consider a service that retrieves a customer by ID:
async function getCustomer(customerId, customerRepository) {
const customer = await customerRepository.findById(
customerId
);
if (!customer) {
throw new Error("Customer not found");
}
return customer;
}A unit test can provide a mock repository:
const assert = require("node:assert/strict");
const test = require("node:test");
test("returns a customer when the record exists", async () => {
const repository = {
findById: async () => ({
id: 10,
name: "Alex"
})
};
const customer = await getCustomer(10, repository);
assert.equal(customer.name, "Alex");
});This test verifies the service behavior, but it does not verify whether the repository can execute its actual SQL query.
For example, the real repository might contain:
SELECT customer_id, customer_name
FROM customers
WHERE customer_id = $1;A mocked test cannot detect problems such as:
The customers table does not exist.
The column is named customer_name instead of name.
A migration did not create the expected index.
A database constraint rejects the inserted record.
A transaction does not roll back as expected.
The application uses a database-specific feature incorrectly.
A real database integration test can identify these issues because it executes the application code against an actual database engine.
Mocking and real database testing serve different purposes. Unit tests should remain fast and focused, while integration tests should verify the interaction between application code and the database.
Understanding Temporary Databases for Testing
A temporary database is an isolated database environment created specifically for a test run.
The typical workflow looks like this:
<escape> Start test environment | v Start temporary database | v Connect Node.js application | v Apply database migrations | v Execute integration tests | v Close database connections | v Remove temporary database </escape>
The important benefit is isolation.
A test should not depend on records created by another developer or another test run. It should also avoid changing data in a shared development or production-like database.
A temporary database provides a predictable environment that can be created again whenever the tests run.
For this example, we will use PostgreSQL, Node.js, the pg database driver, and Testcontainers.
Setting Up the Node.js Project
Create a new project:
mkdir node-database-tests
cd node-database-tests
npm init -yInstall the PostgreSQL driver and Testcontainers PostgreSQL module:
npm install pg
npm install --save-dev @testcontainers/postgresqlThe pg package allows the application to connect to PostgreSQL.
The @testcontainers/postgresql package provides a PostgreSQL container implementation that can be started and controlled from Node.js tests.
You also need Docker or another compatible container runtime available to the machine running the tests.
Check that the container runtime is available before executing the test suite.
For this example, use the following project structure:
node-database-tests/
|
|-- src/
| |-- customer-repository.js
|
|-- test/
| |-- customer-repository.test.js
|
|-- package.jsonCreating the Customer Repository
Before writing the integration test, create a repository that performs actual database operations.
Create src/customer-repository.js:
class CustomerRepository {
constructor(pool) {
this.pool = pool;
}
async create(name, email) {
const result = await this.pool.query(
`INSERT INTO customers (name, email)
VALUES ($1, $2)
RETURNING id, name, email`,
[name, email]
);
return result.rows[0];
}
async findById(id) {
const result = await this.pool.query(
`SELECT id, name, email
FROM customers
WHERE id = $1`,
[id]
);
return result.rows[0] || null;
}
async findByEmail(email) {
const result = await this.pool.query(
`SELECT id, name, email
FROM customers
WHERE email = $1`,
[email]
);
return result.rows[0] || null;
}
async deleteAll() {
await this.pool.query(
"DELETE FROM customers"
);
}
}
module.exports = CustomerRepository;The repository receives a PostgreSQL connection pool through its constructor.
This design makes the repository easier to test because the test can create a real pool connected to the temporary database and pass it into the repository.
The application code does not need to know whether the database is a local development instance, a temporary test container, or a production database.
Starting a Temporary PostgreSQL Database
Now create the integration test.
Create test/customer-repository.test.js:
const test = require("node:test");
const assert = require("node:assert/strict");
const { Pool } = require("pg");
const {
PostgreSqlContainer
} = require("@testcontainers/postgresql");
const CustomerRepository = require(
"../src/customer-repository"
);
let postgres;
let pool;
let repository;
test("Customer repository integration tests", async (t) => {
postgres = await new PostgreSqlContainer(
"postgres:16-alpine"
)
.withDatabase("testdb")
.withUsername("testuser")
.withPassword("testpassword")
.start();
pool = new Pool({
connectionString: postgres.getConnectionUri()
});
repository = new CustomerRepository(pool);
await pool.query(`
CREATE TABLE customers (
id SERIAL PRIMARY KEY,
name VARCHAR(150) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE
)
`);
await t.test(
"creates and retrieves a customer",
async () => {
const created = await repository.create(
"Alex Morgan",
"[email protected]"
);
assert.ok(created.id);
assert.equal(created.name, "Alex Morgan");
const customer = await repository.findById(
created.id
);
assert.equal(customer.email, "[email protected]");
}
);
await t.test(
"returns null when a customer does not exist",
async () => {
const customer = await repository.findById(
999999
);
assert.equal(customer, null);
}
);
await t.test(
"finds a customer by email",
async () => {
const created = await repository.create(
"Taylor Smith",
"[email protected]"
);
const customer = await repository.findByEmail(
"[email protected]"
);
assert.equal(customer.id, created.id);
}
);
await t.test(
"rejects duplicate email addresses",
async () => {
await repository.create(
"Jordan Lee",
"[email protected]"
);
await assert.rejects(
repository.create(
"Another Customer",
"[email protected]"
),
{
code: "23505"
}
);
}
);
await pool.end();
await postgres.stop();
});This example demonstrates the complete lifecycle.
The PostgreSQL container starts before the tests run. The test creates a connection pool using the container's connection URI and creates the customers table.
Each test executes actual SQL against PostgreSQL.
The duplicate email test is particularly useful because it verifies a real database constraint. A mocked repository would not automatically prove that PostgreSQL rejects duplicate email addresses.
The final cleanup closes the connection pool and stops the container.
Join the conversation! Your thoughts help the community grow.