跳转到主要内容
niceeval/expect 提供一组可组合 matcher,传给 t.check()t.require()。matcher 会返回一个 Assertion,并带有默认严重性:gatesoft
import { includes, equals, matches, similarity, satisfies } from "niceeval/expect";

使用方式

t.check(t.reply, includes("confirmed"));
t.check(turn.data, equals({ intent: "refund" }));
t.require(turn.status, equals("completed"));
方法失败时适合
t.check记录结果,继续执行大多数断言
t.require立即抛出,中断 test后续执行没有意义的前置条件

Matchers

includes

includes(substring: string | RegExp): Assertion
断言字符串包含指定子串,或匹配正则。
t.check(t.reply, includes("Paris"));
t.check(t.reply, includes(/order #\d+/i));

equals

equals(expected: unknown): Assertion
断言深度结构相等,适合 JSON、数组和对象。
t.check(turn.data, equals({ intent: "refund" }));

matches

matches(pattern: RegExp): Assertion
断言字符串匹配正则。
t.check(t.reply, matches(/#[A-Z0-9]{8}/));

similarity

similarity(expected: string): Assertion
用于语义或文本相似度检查,通常配合阈值。
t.check(t.reply, similarity("The answer explains the refund window").atLeast(0.8));

satisfies

satisfies(predicate: (value: unknown) => boolean): Assertion
用自定义谓词检查值。
t.check(turn.data, satisfies((value) => Array.isArray(value)));

gate 和 soft

t.check(t.reply, includes("required").gate());
t.check(t.reply, includes("nice to have").atLeast(0.7));
  • gate():失败会让 eval 失败。
  • soft():参与评分,但不一定让 eval 失败。

自定义 matcher

import { makeAssertion } from "niceeval/expect";

const validEmail = makeAssertion("valid email", (value) => {
  return typeof value === "string" && value.includes("@") ? 1 : 0;
});

t.check(t.reply, validEmail());
自定义 matcher 应返回 0 到 1 之间的分数,并给出清晰名称。