Registry / testing / typeorm-test-transactions

typeorm-test-transactions

JSON →
library3.6.1jsnpmunverified

typeorm-test-transactions is a utility library (current stable version 3.6.1) designed to facilitate isolated, concurrent testing for applications using TypeORM. It wraps individual tests in database transactions, ensuring that any data modifications made during a test are automatically rolled back upon completion. This approach prevents test data contamination, allowing tests to run in parallel directly against the database without requiring complex `WHERE` clauses or entity tracking to filter out artifacts from other tests. The library leverages `typeorm-transactional-cls-hooked` for its core transactional capabilities and supports various database versions including MySQL (5.7, 8.0), MariaDB 10, and Postgres (9-13). It differentiates itself from mocking strategies by enabling direct database interaction, crucial for testing database constraints and their impact on application logic.

npm install typeorm-test-transactions
INSTALL
IMPORT
SIG · TYPEORM-TEST-TRANS
T
typeorm-test-transactions
testingjavascriptv3.6.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

runInTransaction
import { runInTransaction } from 'typeorm-test-transactions';
const { runInTransaction } = require('typeorm-test-transactions');
The library primarily uses ES module syntax. CommonJS `require` is generally discouraged for new projects.
initialiseTestTransactions
import { initialiseTestTransactions } from 'typeorm-test-transactions';
import initialiseTestTransactions from 'typeorm-test-transactions';
This is a named export, not a default export. It must be called once before your tests run.

This quickstart demonstrates how to set up `typeorm-test-transactions` with a basic TypeORM `DataSource` and wrap individual test cases using `runInTransaction`. It verifies that database changes are automatically rolled back after a test completes, ensuring isolation between tests.

import { runInTransaction, initialiseTestTransactions } from 'typeorm-test-transactions'; import { DataSource } from 'typeorm'; // Mock or provide your TypeORM DataSource // In a real application, this would come from your setup (e.g., NestJS module) const mockDataSource = new DataSource({ type: 'sqlite', database: ':memory:', synchronize: true, entities: [], }); initialiseTestTransactions(); describe('UserService', () => { let dataSource: DataSource; beforeAll(async () => { dataSource = await mockDataSource.initialize(); }); afterAll(() => { return dataSource.destroy(); }); it('should create a user and roll back', async () => { await runInTransaction(async () => { // Simulate some database operation const queryRunner = dataSource.createQueryRunner(); await queryRunner.connect(); await queryRunner.manager.query('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)'); await queryRunner.manager.query("INSERT INTO users (name) VALUES ('Test User')"); const result = await queryRunner.manager.query('SELECT COUNT(*) FROM users'); expect(result[0]['COUNT(*)']).toBe(1); await queryRunner.release(); }); // After runInTransaction, the changes should be rolled back. // If we try to query now, the table or data should not exist. const queryRunner = dataSource.createQueryRunner(); await queryRunner.connect(); // This query might fail or return 0, depending on database and exact setup const countAfterRollback = await queryRunner.manager.query('SELECT COUNT(*) FROM users').catch(() => 0); await queryRunner.release(); // Expect 0 or an error indicating table not found, demonstrating rollback. // For sqlite :memory:, the table disappears. Adjust expectation for other DBs. expect(countAfterRollback).toBe(0); }); it('should allow another transaction in parallel', async () => { await runInTransaction(async () => { // This test runs in its own isolated transaction const queryRunner = dataSource.createQueryRunner(); await queryRunner.connect(); await queryRunner.manager.query('CREATE TABLE other_table (id INTEGER PRIMARY KEY)'); await queryRunner.release(); }); // Rollback ensures isolation }); });
Debug
Known issues
gotchaThis library may not behave consistently when directly using the `TypeORM` entity manager outside of `typeorm-transactional-cls-hooked`'s `@Transactional` decorator. Data changes might persist to the database even within a `runInTransaction` block if not properly managed through the underlying library's context.
fix
For full consistency, especially with service layers, consider explicitly integrating and using `typeorm-transactional-cls-hooked`'s `@Transactional` decorator on methods that perform database operations, ensuring they operate within the transaction context established by `typeorm-test-transactions`.
affects: >=1.0.0
gotchaRequires TypeORM and reflect-metadata to be installed separately. While `typeorm-test-transactions` depends on `typeorm-transactional-cls-hooked`, the core TypeORM library and `reflect-metadata` are peer dependencies or expected to be present in the consuming project's environment.
fix
Ensure `npm install --save typeorm reflect-metadata` is run in your project alongside `npm install --save typeorm-test-transactions`.
affects: >=1.0.0
Upgrade
Version history
3.6.1latest on npm
Audit
Dependencies
typeormrequiredCore ORM dependency for database interaction.
reflect-metadatarequiredRequired for TypeORM's decorator-based metadata handling.
Agent activity
20 hits · last 30 days
node
16
Meta
1
Amazon
1
OpenAI (training)
1
Resources