# @chax-at/transactional-prisma-testing 中文文档

规范地址：https://npmcn.com/package/%40chax-at/transactional-prisma-testing/

版本：1\.5\.0
npm 元数据更新时间：2026-01-09T12:57:02.740Z
中文译文更新时间：2026-11-09T11:31:17.667Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40chax-at/transactional-prisma-testing
原文对照：https://npmcn.com/package/%40chax-at/transactional-prisma-testing/?lang=original
项目主页：https://github.com/chax-at/transactional-prisma-testing#readme
源码仓库：https://github.com/chax-at/transactional-prisma-testing

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：23.7 kB，7 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>= 14
- 运行依赖：0 个
- peer 依赖：@prisma/client ^4\.7\.0 \|\| 5 \|\| 6 \|\| 7
- 首次发布：2022-05-02T12:47:25.368Z
- 最新版本发布：2026-01-09T12:57:02.325Z
- 近 30 天下载量：153418（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：25（近 12 个月 3 个）

## 中文简介

为在每次测试后回滚快速测试的交易中执行数据库测试提供一种简单的方式

## 安装

```sh
npm install @chax-at/transactional-prisma-testing
```

也可以使用：`pnpm add @chax-at/transactional-prisma-testing`、`yarn add @chax-at/transactional-prisma-testing`、`bun add @chax-at/transactional-prisma-testing`

## README

# @chax-at/ 交易 - prisma - 测试

此软件包提供了在单个数据库交易中运行测试大小写的一个简单方法 每次测试后都要回滚 这允许快速测试执行,同时仍然为每次测试提供相同的源数据库状态. 它还允许对同一数据库进行并行测试执行.

## 先决条件

-   您正在使用 [普里斯马](https://github.com/prisma/prisma) 4.7.0或以后在你的项目.
-   您正在使用 PostgreSQL( 其他 DB 可能有效但还没有测试) .
-   您没有使用 [流利的 API](https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#fluent-api)。 。 。 .

## 使用量

通过运行安装软件包

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

请注意,这将将包装为 Dev 依赖性,仅用于测试(删除 `-D` 若你想在测试之外使用).

### 示例

以下例子说明: [网点JS](https://github.com/nestjs/nest) 项目显示如何使用此软件包. 然而,使用这个包与每个测试框架是可能的,只需查看下面的文件并相应修改代码. 你可以简单地替换 `PrismaService` 与 `PrismaClient` 如果你没有使用NestJS.

```typescript
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` 为棱镜客户端提供代理,并管理此代理.

#### 构造器( 主机: T)

创建单个 `PrismaTestingHelper` 每个测试跑者(或如果测试按顺序执行的单个全局跑者). 构造参数为原始 `PrismaClient` 用于开始交易. 请注意,可以使用任何扩展 PrismaClient 的对象,例如 a [NestJS 棱镜服务](https://docs.nestjs.com/recipes/prisma#use-prisma-client-in-your-nestjs-services)。 。 。 . 棱镜交易客户端上不存在的所有方法都会被路由到这个原始对象(除了 `$transaction` 电话).

#### 获取ProxyClient (): T

此方法返回 a [代理服务器](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) 到 PrismaClient 执行交易中的所有呼叫. 您可以保存并缓存此引用, 所有调用都会在最新的交易中执行 . 这允许您使用代理客户端而不是普通客户端启动您的应用程序 然后执行所有测试大小写,所有的呼叫都会被传送到最新的交易中.

通常只需一次取出,然后在任何地方都使用这个参考.

#### 启动新交易( 选择 ? ): {超时 ?: 数; 最大等待 : 数} : 保证< 无效>

开始新的交易。 必须在每次测试前调用(并且应该在代理客户端上的任何查询执行之前调用). 您可以提供超时值 - 注意交易 `timeout` 一定足够长,所以你 将在此暂停期间执行整个测试例 .

你必须打电话 `rollbackCurrentTransaction` 在再次使用这种方法之前.

#### 回滚当前交易( I): 无效

结束当前活动交易。 每次测试后必须调用, 才能开始新的交易 .

## 限制/洞穴

-   [流利的 API](https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#fluent-api) 不被支持.
-   交易回滚时不会重设序列(自动递增ID). 如果你在测试中需要特定的身份证明,你可以 [使用 SETVAL 重置所有序列](https://stackoverflow.com/a/41108598) 在每次测试之前.
-   `@default(now())` 在您的计划( 例如: `createdAt` 日期)或类似功能(如:. `CURRENT_TIMESTAMP()` 在 PostgreSQL 中,将总是使用 **交易开始** 时间戳。 因此,所有 `createdAt`\- 时间戳在测试期间将具有相同的价值(因为它们是在同一个交易中执行的)。 如果这种行为有问题(例如,因为您想要在创建日期前找到最新的条目),那么您可以使用 `@default(dbgenerated("statement_timestamp()"))` 改为 `@default(now())` (如果您不依赖默认)`createdAt` = 交易开始时的时间而不是声明行为)
-   通过使用 [邮递SQL 保存点](https://www.postgresql.org/docs/current/sql-savepoint.html)。 。 。 .
    -   如果您正在使用并行交易( 例如 ) . `await Promise.all(/* Multiple calls that will each start transactions */);`然后他们就会 自动被相继执行(否则, Savepoints 将无法工作). 您无需更改代码即可工作 .

## 常见问题

### @chax-at/transactional-prisma-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 和提交记录判断。

