✅ Expect 断言系统
@vitest/expect — Jest expect + Chai 双 API 兼容,非对称匹配器,自定义扩展。
1. 模块定位
Expect 模块是 Vitest 的断言层,它面临一个独特的设计约束:同时兼容 Jest 的 expect API 和 Chai 的 assert 风格。这意味着它不能简单地包装 Chai,而需要建立一个桥接层来统一两种断言范式。
2. 双 API 设计
| API 风格 | 示例 | 来源 |
|---|---|---|
| Jest expect | expect(x).toBe(y) | 内置实现 + Chai 垫片 |
| Chai assert | assert.equal(x, y) | 直接暴露 chai 模块 |
| Chai BDD | expect(x).to.equal(y) | Chai 的 BDD 风格 |
// ★ Expect 模块导出:Jest + Chai 双 API 统一暴露
export { ChaiStyleAssertions } from './chai-style-assertions'
export { JestChaiExpect } from './jest-expect' // Jest → Chai 适配器
export { JestExtend } from './jest-extend'
export { JestAsymmetricMatchers } from './jest-asymmetric-matchers'
export * as chai from 'chai' // ★ 直接暴露 Chai核心适配器:JestChaiExpect 是将 Jest 风格断言(如 expect(x).toBe(y))映射到 Chai 内部的桥梁。每个 Jest 风格的匹配器方法(toBe, toEqual, toContain 等)实际上调用 Chai 的底层断言机制。
3. 非对称匹配器
非对称匹配器(Asymmetric Matchers)允许在 expect 中做部分匹配——不要求完全相等,只验证值的部分属性。典型用法:
expect(user).toEqual(
expect.objectContaining({ name: 'Alice' })
// ★ 只验证 user.name,忽略其他属性
)
| 匹配器 | 用途 |
|---|---|
expect.any(Constructor) | 匹配任意该类型的值 |
expect.anything() | 匹配任意非 null/undefined 值 |
expect.arrayContaining(arr) | 数组包含指定元素 |
expect.objectContaining(obj) | 对象包含指定属性 |
expect.stringContaining(str) | 字符串包含子串 |
expect.stringMatching(regexp) | 字符串匹配正则 |
expect.schemaMatching(schema) | 模式匹配(Vitest 扩展) |
| 🏗️ 学习主题 | 关键收获 |
|---|---|
| 双 API 桥接 | Chai 作引擎 + Jest 适配层——保持两个社区的兼容性 |
| 非对称匹配器 | 继承 AsymmetricMatcher 基类 —— 部分匹配模式 |
| 自定义扩展 | expect.extend() 运行时注入——开放封闭原则 |
| 状态管理 | .not / .resolves / .rejects 通过状态标志实现 |