@chax-at/transactional-prisma-testing

中文文档
1.5.0发布于 2026/01/09MITTypeScriptCommonJS零依赖构建来源已验证近 30 天下载 15.3万

Provides an easy way to execute database tests in a transaction that will be rolled back after each test for fast testing

原始使用文档
文档目录5 节
  1. Prerequisites
  2. Usage
  3. Example
  4. PrismaTestingHelper
  5. Limitations / Caveats

@chax-at/transactional-prisma-testing

This package provides an easy way to run test cases inside a single database transaction that will be rolled back after each test. This allows fast test execution while still providing the same source database state for each test. It also allows parallel test execution against the same database.

Prerequisites

  • You are using Prisma 4.7.0 or later in your project.
  • You are using PostgreSQL (other DBs might work but have not been tested).
  • You are not using Fluent API.

Usage

Install the package by running

npm i -D @chax-at/transactional-prisma-testing

Note that this will install the package as a dev dependency, intended to be used during tests only (remove the -D if you want to use it outside of tests).

Example

The following example for a NestJS project shows how this package can be used. It is however possible to use this package with every testing framework, just check out the documentation below and adapt the code accordingly. You can simply replace the PrismaService with PrismaClient if you are not using NestJS.

import { PrismaTestingHelper } from '@chax-at/transactional-prisma-testing';

// Cache for the PrismaTestingHelper. Only one PrismaTestingHelper should be instantiated per test runner (i.e. only one if your tests run sequentially).
let prismaTestingHelper: PrismaTestingHelper<PrismaService> | undefined;
// Saves the PrismaService that will be used during test cases. Will always execute queries on the currently active transaction.
let prismaService: PrismaService;

// This function must be called before every test
async function before(): Promise<void> {
  if(prismaTestingHelper == null) {
    // Initialize testing helper if it has not been initialized before
    const originalPrismaService = new PrismaService(); // in newer prisma versions, you may have to pass an adapter here
    // Seed your database / Create source database state that will be used in each test case (if needed)
    // ...
    prismaTestingHelper = new PrismaTestingHelper(originalPrismaService);
    // Save prismaService. All calls to this prismaService will be routed to the currently active transaction
    prismaService = prismaTestingHelper.getProxyClient();
  }

  await prismaTestingHelper.startNewTransaction();
}

// This function must be called after every test
function after(): void {
  prismaTestingHelper?.rollbackCurrentTransaction();
}

// NestJS specific code: Replace the original PrismaService when creating a testing module
// Note that it is possible to cache this result and use the same module for all tests. The prismaService will automatically route all calls to the currently active transaction
function getMockRootModuleBuilder(): TestingModuleBuilder {
  return Test.createTestingModule({
    imports: [AppModule],
  }).overrideProvider(PrismaService)
    .useValue(prismaService);
}

PrismaTestingHelper

The PrismaTestingHelper provides a proxy to the prisma client and manages this proxy.

constructor(prismaClient: T)

Create a single PrismaTestingHelper per test runner (or a single global one if tests are executed sequentially). The constructor parameter is the original PrismaClient that will be used to start transaction. Note that it is possible to use any objects that extend the PrismaClient, e.g. a NestJS PrismaService. All methods that don't exist on the prisma transaction client will be routed to this original object (except for $transaction calls).

getProxyClient(): T

This method returns a Proxy to the PrismaClient that will execute all calls inside a transaction. You can save and cache this reference, all calls will always be executed inside the newest transaction. This allows you to e.g. start your application once with the ProxyClient instead of the normal client and then execute all test cases, and all calls will always be routed to the newest transaction.

It is usually enough to fetch this once and then use this reference everywhere.

startNewTransaction(opts?: { timeout?: number; maxWait?: number}): Promise<void>

Starts a new transaction. Must be called before each test (and should be called before any query on the proxy client is executed). You can provide timeout values - note that the transaction timeout must be long enough so that your whole test case will be executed during this timeout.

You must call rollbackCurrentTransaction before calling this method again.

rollbackCurrentTransaction(): void

Ends the currently active transaction. Must be called after each test so that a new transaction can be started.

Limitations / Caveats

  • Fluent API is not supported.
  • Sequences (auto increment IDs) are not reset when transaction are rolled back. If you need specific IDs in your tests, you can reset all sequences by using SETVAL before each test.
  • @default(now()) in your schema (e.g. for a createdAt date) or similar functionality (e.g. CURRENT_TIMESTAMP() in PostgreSQL) will always use the start of transaction timestamp. Therefore, all createdAt-timestamps will have the same value during a test (because they are executed in the same transaction). If this behavior is problematic (e.g. because you want to find the latest entry by creation date), then you can use @default(dbgenerated("statement_timestamp()")) instead of @default(now()) (if you do not rely on the default "createdAt = time at start of transaction instead of statement" behavior)
  • Transactions in test cases are completely supported by using PostgreSQL Savepoints.
    • If you are using parallel transactions (e.g. await Promise.all(/* Multiple calls that will each start transactions */);), then they will automatically be executed sequentially (otherwise, Savepoints wouldn't work). You do not have to change your code for this to work.

版本与发布记录

@chax-at/transactional-prisma-testing 共发布 25 个版本,首次发布于 2022/05/02;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.5.0latest2026/01/099 个月前
1.4.22025/11/1711 个月前
1.4.12025/11/1311 个月前
1.4.02025/09/161.1 年前
1.3.12025/01/231.8 年前
1.3.1-extension-fix.12025/01/151.8 年前

关于 @chax-at/transactional-prisma-testing 的常见问题

@chax-at/transactional-prisma-testing 是什么?

Provides an easy way to execute database tests in a transaction that will be rolled back after each test for fast testing

如何安装 @chax-at/transactional-prisma-testing?

在项目目录运行 npm install @chax-at/transactional-prisma-testing,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@prisma/client(^4.7.0 || 5 || 6 || 7)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@chax-at/transactional-prisma-testing 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@chax-at/transactional-prisma-testing 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@chax-at/transactional-prisma-testing 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 14。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@chax-at/transactional-prisma-testing 可以商用吗?

@chax-at/transactional-prisma-testing 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@chax-at/transactional-prisma-testing 的下载量有多少?

根据 npm 官方下载统计,@chax-at/transactional-prisma-testing 在 2026/10/10 – 2026/11/08 这 30 天内被下载 153,418 次,日均约 5,114 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@chax-at/transactional-prisma-testing 还在维护吗?

最新版本 1.5.0 发布于 2026/01/09(9 个月前);至今共发布 25 个版本,其中过去 12 个月发布了 3 个;首次发布于 2022/05/02。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。