pi-agent - Vitest Usage

describe 和 it

这是 Vitest(一个测试框架,类似 Jest)提供的两个核心函数,来自 第 3 行 的导入:

import { describe, expect, it } from "vitest";

describe —— 分组

describe("Agent", () => {
    // 所有测试放在这里面
    it("...", () => { ... });
    it("...", () => { ... });
});

把一组相关的测试包在一起,形成一个测试套件。输出时会显示层级关系:

Agent
  ✓ should create an agent instance with default state
  ✓ should subscribe to events
  ✗ should throw when prompt() called while streaming

一个文件里可以有多个 describe,嵌套也没问题。

it —— 单个测试用例

it("should create an agent instance with default state", () => {
    const agent = new Agent({ streamFn: unusedStreamFunction });
    expect(agent.state.systemPrompt).toBe("");
});

it 定义一个具体的测试,第一个参数是描述性名称(通常以动词开头),第二个参数是测试逻辑。也可以写成 test("...", () => { ... }),效果完全一样。

expect —— 断言

配合 it 使用,验证结果是否符合预期:

expect(agent.state.isStreaming).toBe(false);    // 等于
expect(agent.state.messages).toEqual([]);       // 深度相等
await expect(agent.prompt("hi")).rejects.toThrow("..."); // 应该抛错

完整结构

describe("Agent", () => {          // 分组:测试 Agent 这个类
    it("should create ...", () => {  // 用例 1:测试创建
        // 准备 → 执行 → 断言
    });

    it("should subscribe ...", () => { // 用例 2:测试订阅
        // 准备 → 执行 → 断言
    });
});

关键特性

特性 说明
it 可以是异步的 直接传 async 函数即可:it("...", async () => { await ... })
一个 it 失败不影响其他 每个用例独立运行
describe 可以嵌套 用来组织更细粒度的分组
it.skip / it.only 跳过某个测试 / 只运行这一个

简单总结:describe 是文件夹,it 是文件,expect 是检查清单。


posted @ 2026-09-18 21:34  lukefoto  阅读(15)  评论(0)    收藏  举报