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 -y
Install the PostgreSQL driver and Testcontainers PostgreSQL module:
npm install pg
npm install --save-dev @testcontainers/postgresql
The 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.json
Creating 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.
For a production-quality test suite, cleanup should be placed in a guaranteed teardown hook so that the database is stopped even if a test fails. We will improve that implementation shortly.
Running the Integration Tests
Node.js includes a built-in test runner, so a separate testing framework is not required for this example.
Add a test script to package.json:
{
"scripts": {
"test": "node --test"
}
}
Run the tests:
npm test
The test runner discovers test files and executes them.
The first run may take longer because the container image needs to be downloaded if it is not already available locally.
After the container starts, the tests connect to the temporary PostgreSQL instance and execute their queries.
When the test completes, the container is stopped and its temporary database environment is removed.
The exact execution time depends on the machine, container runtime, database image availability, and number of tests.
Improving Cleanup With Test Hooks
The previous example places cleanup at the end of the parent test. However, if an assertion fails or an unexpected error occurs before those statements execute, resources may remain open.
Node.js provides before(), after(), beforeEach(), and afterEach() hooks through its test module.
A cleaner implementation uses after() for resource cleanup:
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.before(async () => {
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
)
`);
});
test.after(async () => {
if (pool) {
await pool.end();
}
if (postgres) {
await postgres.stop();
}
});
test("creates a customer", async () => {
const customer = await repository.create(
"Morgan Reed",
"[email protected]"
);
assert.equal(customer.name, "Morgan Reed");
});
The before() hook starts the database and prepares the repository before the tests execute.
The after() hook closes the connection pool and stops the container after the test suite completes, including when a test fails.
For more complex test suites, keep cleanup operations independent so that a failure while closing one resource does not prevent the application from attempting to clean up another resource.
Applying Real Database Migrations
Creating tables directly inside a test is convenient for a small example, but production applications usually manage database structure through migrations.
A migration may create tables, add indexes, change column types, or introduce constraints.
Integration tests should verify that the actual application migrations can build the database schema correctly.
For example, if the project uses a migration tool, run its migration command after the temporary database starts.
The general sequence should be:
- Start the temporary PostgreSQL container.
- Create the database connection configuration.
- Execute the application's migration process.
- Run repository and service integration tests.
- Close connections and stop the container.
Avoid maintaining a separate test-only schema that gradually becomes different from the production schema.
Testing the real migrations helps detect missing migrations, incorrect SQL, unsupported database operations, and unexpected dependencies between schema changes.
Also, keep database migrations deterministic. A migration should not depend on records or database objects that happen to exist in a developer's local environment.
Keeping Tests Isolated
A temporary database gives the test suite an isolated environment, but individual tests can still affect each other.
For example, one test may insert a customer, and another test may expect the customers table to be empty.
If tests share the same database without a cleanup strategy, their results can depend on execution order. There are several ways to manage test isolation.
|
Strategy
|
How it works
|
Suitable use
|
|
Delete test records
|
Removes inserted data after each test
|
Small integration suites
|
|
Truncate tables
|
Clears selected tables between tests
|
Tests that share a schema
|
|
Database transactions
|
Rolls back changes after a test
|
Repositories using the same transaction connection
|
|
Separate schemas
|
Gives each test group its own schema
|
Larger parallel test suites
|
|
Separate containers
|
Gives test groups independent database instances
|
Tests requiring complete isolation
|
Transactions can be useful, but they require careful design. If the application creates its own connection pool and repository methods use different connections, a transaction opened on one connection will not automatically contain operations performed on another connection.
For transaction-based tests, ensure that every operation under test uses the same transaction connection or a transaction-aware repository abstraction.
For many integration suites, a shared temporary database with carefully controlled test data is sufficient.
Testing Database Constraints and Transaction Behavior
One of the main advantages of using a real database is the ability to verify behavior that mocks often miss.
Consider a transaction that creates an order and its order items. Both operations should succeed together or fail together.
A simplified example using PostgreSQL:
async function createOrder(pool, customerId, items) {
const client = await pool.connect();
try {
await client.query("BEGIN");
const orderResult = await client.query(
`INSERT INTO orders (customer_id)
VALUES ($1)
RETURNING id`,
[customerId]
);
const orderId = orderResult.rows[0].id;
for (const item of items) {
await client.query(
`INSERT INTO order_items
(order_id, product_id, quantity)
VALUES ($1, $2, $3)`,
[
orderId,
item.productId,
item.quantity
]
);
}
await client.query("COMMIT");
return orderId;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
An integration test can create a valid customer, execute the transaction, and verify that both the order and its items exist.
Another test can intentionally use an invalid product ID and verify that the transaction rolls back.
This checks actual foreign-key enforcement and transaction behavior rather than relying on assumptions in a mock implementation.
Running Temporary Database Tests in CI
Temporary database containers are also useful in continuous integration pipelines.
A GitHub Actions workflow can install Node.js dependencies and execute the test suite on a runner that supports Docker.
For example:
name: Node.js Integration Tests
on:
push:
branches:
- main
pull_request:
permissions:
contents: read
jobs:
integration-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- name: Install dependencies
run: npm ci
- name: Run integration tests
run: npm test
Testcontainers detects the available container runtime and starts the database as part of the test execution.
The workflow does not need to connect to a shared database server. Each test run receives its own temporary database environment.
For a production workflow, use reviewed action versions and ensure that the selected runner supports the required container operations.
Common Mistakes When Testing With Temporary Databases
Using a Different Database Engine
An application that uses PostgreSQL should be tested against PostgreSQL rather than assuming that SQLite or an in-memory database behaves identically.
Different database engines have different SQL syntax, transaction behavior, data types, locking mechanisms, and constraint implementations.
Use the same database engine as the application whenever database compatibility is important.
Forgetting to Close Connection Pools
Stopping a container while the application still has active database connections can cause cleanup problems.
Close the connection pool before stopping the database container.
Sharing Test Data Between Tests
Tests that depend on previously inserted records become fragile when execution order changes.
Use independent test data and an explicit cleanup strategy.
Running Too Many Containers
Starting a separate database container for every individual test can create unnecessary overhead.
For many applications, one container per test suite is a reasonable starting point. Use separate containers when tests require stronger isolation or different database configurations.
Ignoring Migration Testing
Creating tables manually in tests can hide problems in the application's real migration process.
Run the same migrations used by the application before executing integration tests.
Depending on a Shared Development Database
Shared databases introduce unpredictable test results because other developers or processes can modify the data.
Temporary databases provide a cleaner and more repeatable testing environment.
Summary
Testing Node.js applications against temporary real databases helps identify problems that mocked database tests cannot reliably detect. It verifies actual SQL execution, constraints, transactions, data types, and database behavior. Testcontainers makes it practical to start a temporary PostgreSQL instance directly from a Node.js test suite. The application can connect through its normal database driver, execute migrations, run integration tests, and remove the database environment afterward.
For reliable results, use the same database engine as production, isolate test data, close connection pools correctly, and execute the real migration process. Combine these integration tests with focused unit tests rather than replacing one testing approach with the other.
A temporary database gives developers a repeatable environment for testing database-dependent code without relying on shared infrastructure. This makes integration testing more predictable and helps catch database problems before application changes reach production.