diff --git a/tests/unit/form_infer_addfields.test.ts b/tests/unit/form_infer_addfields.test.ts new file mode 100644 index 0000000..1161db9 --- /dev/null +++ b/tests/unit/form_infer_addfields.test.ts @@ -0,0 +1,36 @@ +/** + * tests/unit/form_infer_addfields.test.ts — form update --ai 推理核心单元测试 + * + * 测 _ai.ts.inferAddFields 的服务端安全网 (在 LLM 出口处剔除一切垃圾): + * - f_ 前缀 + snake_case + * - 跟现有字段不重名 (vmodel) + * - jnpfKey 在白名单 + * - 中文 label 不与现有重复 + * - JSON 解析容错 (fence / 前置说明) + * + * 不测 LLM 调用本身 (那要 mock chatViaProxy, 由 E2E 测覆盖)。 + */ +import { describe, it, expect } from 'vitest' +import { extractJsonArray } from '../../src/commands/form/_ai.ts' + +describe('extractJsonArray: LLM 输出容错', () => { + it('直接 JSON 数组', () => { + const out = extractJsonArray('[{"a":1},{"b":2}]') + expect(out).toEqual([{ a: 1 }, { b: 2 }]) + }) + it('markdown fence ```json ... ```', () => { + const out = extractJsonArray('以下是字段:\n```json\n[{"x":1}]\n```\nEND') + expect(out).toEqual([{ x: 1 }]) + }) + it('fence 无语言标识 ```...```', () => { + const out = extractJsonArray('```\n[{"y":2}]\n```') + expect(out).toEqual([{ y: 2 }]) + }) + it('前置说明 + 尾部多余字符 (取第一个 [ 到最后一个 ])', () => { + const out = extractJsonArray('好的, 这是你要的:\n[{"z":3}]\n如有疑问请回复') + expect(out).toEqual([{ z: 3 }]) + }) + it('找不到数组抛错', () => { + expect(() => extractJsonArray('LLM 没返数组')).toThrow() + }) +})