# @checksum-ai/runtime 中文文档

规范地址：https://npmcn.com/package/%40checksum-ai/runtime/

版本：5\.5\.2
npm 元数据更新时间：2026-11-04T01:34:38.319Z
中文译文更新时间：2026-11-09T11:49:13.949Z
软件包许可：ISC

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

原始 npm 页面：https://www.npmjs.com/package/%40checksum-ai/runtime
原文对照：https://npmcn.com/package/%40checksum-ai/runtime/?lang=original
项目主页：https://github.com/checksum-ai/checksum-ai-monorepo/tree/main/packages/runtime#readme
源码仓库：https://github.com/checksum-ai/checksum-ai-monorepo

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

- 包体积（解压后）：6.2 MB，33 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=20\.18
- 运行依赖：11 个
- 首次发布：2023-11-16T13:04:02.639Z
- 最新版本发布：2026-11-04T01:34:38.156Z
- 近 30 天下载量：47985（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：442（近 12 个月 208 个）

## 中文简介

Checksum.ai 测试运行时间

## 安装

```sh
npm install @checksum-ai/runtime
```

也可以使用：`pnpm add @checksum-ai/runtime`、`yarn add @checksum-ai/runtime`、`bun add @checksum-ai/runtime`

## README

# 验收 运行时间

### 快速启动

1.  使用软件包安装 `npm install -D checksumai` 或者说 `yarn add checksumai -D`。 。 。 .
2.  导航到目录中要初始化校验和测试文件夹并运行的地方 `npx checksumai init`。 。 。 .
3.  在新创建的 `checksum` 文件夹 :
    1.  定义 `CHECKSUM_API_KEY` 财务报告和审定财务报表 `BASE_URL` 内 `checksum/.env` 或您的外壳; 启动配置读取 `process.env.CHECKSUM_API_KEY` 财务报告和审定财务报表 `process.env.BASE_URL!`。 。 。 .
    2.  更新 `login.ts` 与您的 Playwright 登录流量。 有关当前parms-object API,请参看下面的登录函数部分.
    3.  审查起始示例 `checksum/tests/examples/example.checksum.spec.ts` 财务报告和审定财务报表 `checksum/tests/examples/example.checksum.md`。 。 。 .
    4.  重运行 `npx checksumai init` 之后在不覆盖您已经定制的文件的情况下, 将任何缺失的启动文件回填 .
4.  运行 `npx playwright install --with-deps` 以安装 Playwright 依赖性.
5.  运行 `npx checksumai test` 执行启动器 `.checksum.spec.ts` 示例并验证您的登录设置.
6.  还没有的话就去拜访一下 [app. checksum.ai (英语)](https://app.checksum.ai/) 以完成配置并生成测试。 然后,等待拉动请求(PR)的创建和批准.

### 启动文件

-   `checksum/login.ts` 显示运行时登录回调签名和在哪里 `environment`, (中文(简体) ), `user`,以及 `config` 从来.
-   `checksum/tests/examples/example.checksum.spec.ts` 是一个最小的 TypeScript 启动器 `init()`, (中文(简体) ), `defineChecksumTest(...)`,以及 `login(page)`。 。 。 .
-   `checksum/tests/examples/example.checksum.md` 是一个最小的减速流量启动器。 替换占位符 `appId` 财务报告和审定财务报表 `checksumTestId` 使用前的数值.
-   Repo 镜像同时读取 `.checksum.spec.ts` 财务报告和审定财务报表 `.checksum.md` 文件,因此两个启动格式都在 `checksumai init`。 。 。 .

### 登录函数

1.  此函数在每次测试开始时执行 .
2.  我们建议每次测试都使用一致的种子用户。 例如,在每次测试之前,调用一个创建用户的webhook,用数据种子,并返回用户名和密码. 这种方法确保测试可靠性并允许平行的测试执行. 配置此网点 [在您的项目中](https://app.checksum.ai/#/settings/wizard) 以一致的测试生成.
3.  登录后,断言登录成功. Playwright等待断言正确,确保页面在进行前做好互动准备.
4.  要在测试之间重新使用认证状态,请参考Playwright指南: [认证](https://playwright.dev/docs/auth)。在登录功能开始时,检查用户是否已经认证,如果已经认证,则返回.
5.  使用 `ChecksumLoginFunction` 类型以正确执行登录函数 :
    
    ```
      import { ChecksumLoginFunction } from "@checksum-ai/runtime";
    
      const login: ChecksumLoginFunction = async (
        page,
        { environment, user, config }
      ) => {
        // environment contains the selected environment from checksum.config.ts.
        // user contains the selected credentials for that environment.
        // config is the loaded checksum.config.ts object.
        const loginUrl = environment.loginURL ?? "/login";
    
        await page.goto(loginUrl);
        await page.getByPlaceholder("Email").fill(user.username ?? "");
        await page.getByPlaceholder("Password").fill(user.password ?? "");
        await page.getByRole("button", { name: "Log in" }).click();
        await page.waitForURL(new URL("/", environment.baseURL).toString());
      };
    
      export default login;
    ```
    

当定义多个环境或角色时,帮助者喜欢 `login(page, { environment, role })` 财务报告和审定财务报表 `getEnvironment({ name, userRole })` 决定哪个 `environment` 财务报告和审定财务报表 `user` 到达此函数.

## 校验和 AI 魔法

Checksum生成的测试基于Playwright. 当使用带有API密钥的Checksum runtime CLI执行时,Checksum会增强Playwright的功能,提高测试可靠性并自动维持测试. 每次增强都使用 `checksum.config.ts` 文档.

#### 智能选择器

当生成测试时, 校验和会为每个动作存储大量元数据( 存储于 `checksum/test-data` 文件夹). 如果传统的选择器失败,此元数据用于定位目标元素. 例如,如果一个测试用其ID识别一个元素,但ID更改,Checksum会利用其他数据点(如元素类,文本,父母)来定位该元素. 使用 `checksumSelector("<id>")` 将一个动作与其元数据链接的方法。 不要改变身份证.

#### 校验和AI

如果Smart Selectioners也失败了,Checksum的自定义训练模型可以再生测试失败的部分. 在这种情况下,该模式可以增加、删除或改变实现相同目标的行动,而不改变说法。 假设是,只要断言通过,模型就成功固定了测试. 使用 `checksumAI` 为了实现这一行为,将每个步骤围起来的方法.

使用两者的示例 `checksumSelector` 财务报告和审定财务报表 `checksumAI`数字 :

```js
 await checksumAI("Save the form and continue", () =>
      page
        .checksumSelector("gIexv")
        .getByRole("button", { name: "Save" })
        .click()
    );
```

你可以根据我们的模型修改描述 此外,您还可以包含仅包含ChecksumAI描述的步骤,提示我们的模型生成Playwright代码. 譬如说, `await page.checksumAI("Click on 'New Task' button")` 没有实际行动,我们的模型将产生必要的 Playwright 代码。 你甚至可以这样写整个测试.

### 模拟数据

在生成测试时,Checksum记录所有网络响应,允许测试在同一上下文中运行. 这些录音作为HAR文件存储,保存于 `checksum/test-data/har` 文件夹。 使用这种方法对调试新生成的测试特别有用,特别是如果测试数据库/文本不同于用于测试生成的数据库/文本. 请注意,如果您的网络响应格式发生变化,被模拟的数据可能无法如预期的那样工作.

## 校验和配置

除了标准测试运行配置 `playwright.config.ts`,使用 `checksum.config.ts` 用于配置测试运行的文件.

```js
{
  /**
   * Checksum Run mode.
   * Normal is currently the only supported mode.
   */
  runMode: RunMode.Normal,

  /**
   * Define CHECKSUM_API_KEY in checksum/.env or your shell.
   * You can find it in https://app.checksum.ai/#/settings/
   */
  apiKey: process.env.CHECKSUM_API_KEY,

     /**
   * Define your test run environments and test users within each environment.
   * The environments must be aligned with those set here:
   * https://app.checksum.ai/#/settings/
   */
  environments: [{
      name: 'staging';
      users: [
         {
            role: "host",
            username: "<host username>",
            password: "<host password>",
         },
         {
            role: "guest",
            username: "<guest username>",
            password: "<guest password>",
         },
      ],
      baseURL: 'staging.mydomain.com';
      loginURL: 'staging.mydomain.com/login';
      default: true;
  }]

  options: {
    /**
     * Use Checksum Smart Selector to
     * recover from failing to locate an element for an action
     */
    useChecksumSelectors: true,
    /**
     * Use Checksum AI to
     * recover from a failed action or assertion
     * @actions - enable recovery from checksumAI steps
     * @assertions - enable recovery from assertion steps
     * @visualComparison - enable visual comparison recovery when using toHaveScreenshot assertions 
     */
    useChecksumAI: { actions: true, assertions: false, visualComparison: false },
    /**
     * Whether to use recorded network responses when running your tests
     */
    useMockData: false,
    /**
     * Whether to upload the test reports to Checksum cloud 
     * allowing you to view them at https://app.checksum.ai/#/test-runs.
     * Note: Only relevant if Playwright reporter config is set to HTML
     * Note: Reports will be saved locally either way (according to Playwright configs)
     * and can be viewed using the CLI command show-reports.
     */
    hostReports: !!process.env.CI,
  }
}
```

## 剧作家配置

一个 Playwright 配置文件 `playwright.config.ts` 应该可供 Playwright 测试跑取器使用,以便提供项目配置. 为了方便,我们扩展了配置,允许添加 `playwright-extra-plugins` 软件包. 可用的插件可见于 [https://github.com/berstend/puppeteer-extra/tree/master/packages/playwright-extra 互联网档案馆的存檔,存档日期2014-12-12](https://github.com/berstend/puppeteer-extra/tree/master/packages/playwright-extra)

要添加插件 :

-   使用您的软件包管理器( yarn, npm, pnpm) 安装
-   导入您的插件 `playwright.config.ts` 文件
-   在那个 `projects` 定义 `use`,将其添加到剧作家Extra阵列
-   在添加数组之前或期间确定初始化插件

示例 `playwright.config.ts` 与 `puppeteer-extra-plugin-stealth` 插件 :

```js
import { PuppeteerExtraPlugin } from "puppeteer-extra-plugin";
import StealthPlugin from "puppeteer-extra-plugin-stealth"; // <--- Added import line

export default defineConfig<{ playwrightExtra?: PuppeteerExtraPlugin[] }>({
  // ....
  projects: [
    {
      name: "chromium",
      testMatch: /checksum.spec/,
      use: {
        ...devices["Desktop Chrome"],
        playwrightExtra: [StealthPlugin()], // <--- Initialized and added to the playwrightExtra array
      },
    },
  ],
});
```

**参见内部更详细的说明 `checksum-root/playwright.config.ts` 文件**

## 校验和帮助 API

帮助者从初始呼叫中解析到导入的@ checksum-ai/runtime `init` 方法,如下:

```js
import { test as base } from "@playwright/test";
import { init, IChecksumPage } from "@checksum-ai/runtime";
const { test, expect, defineChecksumTest, login, checksumAI } = init(base);
```

```js
function init(base: ChecksumTestType<PlaywrightTestArgs>): {
   /**
    * The Playwright test instance enhanced by Checksum
    */ 
  test: ChecksumTestType<ChecksumPlaywrightTestArgs>;
  /**
   * The login method which calls the user defined login function
   */
  login: (
    page: Page,
    { role, environment }?: { role?: string; environment?: string }
  ) => Promise<void>;
  /**
   * The test title definition along with the test id
   * used by Checksum to identify the test
   */
  defineChecksumTest: (title: string, testId: string) => string;
     /**
    * The Playwright expect instance enhanced by Checksum
    */ 
  expect: ChecksumExpect;
  /**
   * Wrap each test action with this method to let
   * Checksum recover from failure using our test recover AI agent
   */
  checksumAI: (description: string, testFunction: Function) => Promise<any>;
  /**
   * Return environment data as defined in the checksum configuration 
   * given the environment name and userRole, along with a login function
   * for this environment and user combination
   */
  getEnvironment: ({
    name,
    userRole,
  }: {
    name?: string;
    userRole?: string;
  }) => {
    environment: ChecksumConfigEnvironment;
    user: EnvironmentUser;
    login: (
      page: Page,
      { role }?: { role?: string }
    ) => Promise<void>;
  };
};
```

## 校正和页 API

```js
interface ChecksumPage extends Page {
   /**
    * Affiliates the test step with selection data calculated during test generation and used as part of the recovery mechanism in case Playwright fails to locate the element
    */
  checksumSelector: (id: string) => ChecksumPage;

  /**
   * Wraps a test step allowing ChecksumAI to recover from failures or even generate
   * the required Playwright code when no callback is provided.
   * Can be chained with `.withDialog` to automatically listen to browser dialogs
   * or with `.skipAutoRecovery` to prevent recovery attempts.
   */
  checksumAI: (thought: string, body?: () => any) => Promise<any> | ChecksumPage;

  /**
   * Resolves file-upload asset names against the configured assets folder.
   */
  resolveAssetsFolder: (assets: string[]) => string[];

  /**
   * For multi-tab flows: returns the ChecksumPage by order of appearance, where 0 is the initially opened tab.
   */
  getPage(index: number): Promise<ChecksumPage>;

  /**
   * Creates a compound selection by grouping multiple anchors and optionally
   * resolving a target element relative to their common parent.
   */
  compoundSelection: {
    (
      anchors: (base: Locator) => Array<Locator | string>,
      target?: (base: Locator) => Locator | string
    ): ChecksumLocator;
    (selection: {
      anchors: (base: Locator) => Array<Locator | string>;
      target?: (base: Locator) => Locator | string;
    }): ChecksumLocator;
  };

  /**
   * When required to login mid-test, use reauthenticate with the user's role. Note: It is not possible to change environments during a single test run.
   */
  reauthenticate: (role: string) => Promise<void>;

   /**
   * When required to handle actions that involve browser Native Dialogs that are part of the WebAPI,
   * use waitForDialog to listen for any dialog events, and handle them accordingly inside the handler.
   * Note: waitForDialog can only work within a checksumAI.withDialog call which initiates the dialog listener. 
   * 
   * await checksumAI.withDialog("delete item and confirm", () => {
   *  await page.locator('.delete').click();
   *  await page.waitForDialog().then((confirm) => {
   *      confirm.accept();
   *  });
   * });
   */
  waitForDialog: (timeout?: number) => Promise<Dialog>;
}

```

## 校验和标记 API

ChecksumLocator 扩展了现有的 Playwright Locator , 增加了以下功能 :

-   画布点击
-   复选

```js
interface ChecksumLocator extends Locator {
  /*
   * Click on certain text within the canvas element the locator chain points to.
   * When more than one element with the same text exists, uses the rectSizeIndex
   * to resolve the target element by its bounding box size, 0 being the largest.
   * Example:
   * await page.locator('canvas').canvasClick('graph-point-1', 1); // clicking on the 2nd largest
   */
  canvasClick: (canvasText: string, rectSizeIndex?: number) => Promise<void>;

  /**
   * Will create a compound selection that selects elements by grouping multiple locators as anchors
   * and finding the target elements, if specified, from their common root parent.
   * If no target is provided, the compound selection will return a locator to the common parents that were calculated from the anchors.
   *
   * **Usage example**
   *
   * ```js
   * await page.compoundSelection(
   *  (base) => [base.getByText("<selector to first anchor>""), page.locator("selector to second anchor"), "<text content of third anchor>"],
   *  (base) => base.locator("<relative selector to target element>")
   * ]).first().click();
   * ```
   *
   * @param anchors Method that returns array of locators and/or text context, to group and calculate the common parent from.
   *                The method receives the base locator as an argument, which is the relative locator or page that the compound selection is called on.
   *                The method should return an array of locators or strings that point at the anchor elements.
   * @param target [optional] Method that returns the relative locator or string content that will point at the target element from the common parent
   *               that was calculated from the anchors.
   *               If no target is provided, the compound selection will return a locator pointing at the common parents.
   * @returns Locator to the common parent(s) or the target element(s) if specified.
   */
  compoundSelection(
    anchors: (base: Locator) => Array<Locator | string>,
    target?: (base: Locator) => Locator | string
  ): ChecksumLocator;

  /**
   * Will create a compound selection that selects elements by grouping multiple locators as anchors
   * and finding the target elements, if specified, from their common root parent.
   * If no target is provided, the compound selection will return a locator to the common parents that were calculated from the anchors.
   *
   * **Usage example**
   *
   * ```js
   * await page.compoundSelection({
   *    anchors: (base) => [base.getByText("<selector to first anchor>""), page.locator("selector to second anchor"), "<text content of third anchor>"],
   *    target?: (base) => base.locator("<relative selector to target element>")
   * }).first().click();
   * ```
   * @returns Locator to the common parent(s) or the target element(s) if specified.
   */
  compoundSelection(selection: {
    /**
     * Method that returns array of locators and/or text context, to group and calculate the common parent from.
     * The method receives the base locator as an argument, which is the relative locator or page that the compound selection is called on.
     * The method should return an array of locators or strings that point at the anchor elements.
     *
     * @param base Base locator that the compound selection is called on.
     */
    anchors: (base: Locator) => Array<Locator | string>;
    /**
     * Method that returns the relative locator or string content that will point at the target element from the common parent
     * that was calculated from the anchors.
     * If the target is null, the compound selection will return a locator pointing at the common parents.
     *
     * @param base Base locator that the compound selection is called on.
     */
    target?: (base: Locator) => Locator | string;
  }): ChecksumLocator;
}
```

## CLI 命令

1.  `init` - 初始化校验和目录及配置.
2.  `test` - 运行校验和测试。 接受全部 [播放鼠标命令行旗](https://playwright.dev/docs/test-cli)覆盖 `checksum.config.ts`,通过 JSON 作为字符串 `--cksm-config`启用 `--cksm-title="<message>"` 为运行设置自定义承诺消息.
3.  `show-report` - 本地显示最新的 HTML 运行报告 。 只有在完成配置以输出 HTML 报表的测试运行后才适用 .
4.  `dotenv` - 管理环境变量。 使用 `--download` 下载 `.env` 用于您的项目的文件。 一个 `--api-key` 参数如果不在 `checksum.config.ts`。 。 。 . 实例:
    -   `npx checksumai dotenv --download`
    -   `npx checksumai dotenv --download --api-key=<apiKey>`

## 解决问题

**问:我在进行"npx checkumai测试"时,甚至在测试开始前,就看到各种例外.**

答:如果你有Playwright的预安装版本,它可能与Checksum不相容. 删除 Playwright 和 Checksum 库, 删除相关的文件夹 `node_modules`运行 `npm install -D checksumai`。 。 。 .

## 常见问题

### @checksum-ai/runtime 是什么？

Checksum\.ai 测试运行时间

### 如何安装 @checksum-ai/runtime？

在项目目录运行 npm install @checksum-ai/runtime，或使用 pnpm add / yarn add / bun add。

### @checksum-ai/runtime 支持 TypeScript 吗？

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

### @checksum-ai/runtime 支持 ESM 还是 CommonJS？

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

### @checksum-ai/runtime 需要什么版本的 Node\.js？

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

### @checksum-ai/runtime 可以商用吗？

@checksum-ai/runtime 使用 ISC 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @checksum-ai/runtime 的下载量有多少？

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

### @checksum-ai/runtime 还在维护吗？

最新版本 5\.5\.2 发布于 2026/11/04（5 天前）；至今共发布 442 个版本，其中过去 12 个月发布了 208 个；首次发布于 2023/11/16。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

