Skip to content

AssertionError: Expected 值到 是 equal

错误信息

                expect(接收).toBe(expected) — 对象.是 equality
              

快速摘要

大多数常见测试失败: 你的 assertion expected one 值但 获取 another. 错误消息 shows 两者都值 到 help 你 diagnose mismatch.

为什么发生

  • 函数 under 测试 returned 不同值 than expected — code 有 bug.

  • expected 值 in 测试是 错误 — 测试它自己有 mistake.

  • 测试设置 (排列 phase) didn't prepare 正确输入 or 状态.

  • dependency returned unexpected 数据那个 propagated 通过 code.

最小示例

✗ 错误代码
test('add', () => {
  expect(add(2, 3)).toBe(6); // wrong expectation
});
✓ 修复代码
test('add', () => {
  expect(add(2, 3)).toBe(5); // correct expectation
});

expected 值是 错误 — 2 + 3 = 5, 不 6. Fix 测试 expectation.

如何诊断

  • 读取错误消息 carefully — 它 shows 'Expected: X' and '接收: Y'.

  • 检查如果 expected 值 in 你的测试是 正确通过 reviewing 需求.

  • Manually trace 通过 code 使用测试输入到 see 什么正确输出应该是.

  • 如果 using mocks, 验证 mock 是 returning expected 测试数据.

如何修复

  • 如果 code 是错误, fix implementation 到返回正确值.

  • 如果测试 expectation 是错误, 更新 expected 值 in assertion.

  • 如果设置是 错误, fix 排列 phase 到 provide 正确输入.

如何预防

  • Use descriptive 测试 names 那个 document expected behavior.

  • 开始使用简单情况 and 构建上 到复杂 ones.

  • Use TDD 到 clarify expected behavior 之前 implementation.

相关资源

相关术语

相关课程

← 返回语言