Skip to content

Cannot 读取属性的 undefined

错误信息

                TypeError: Cannot 读取属性的 undefined (读取 'name')
              

快速摘要

code or 测试 tries 到 access 属性 on undefined 值. mock 可能不 是配置到 返回 expected 对象.

为什么发生

  • mock 函数返回 undefined 相反的 expected 对象.

  • code under 测试 doesn't handle 空/undefined 返回从 dependencies.

  • 测试数据是 不完整 — missing nested 属性.

  • 异步操作 returned undefined 相反的 数据.

最小示例

✗ 错误代码
const mockGetUser = jest.fn(); // returns undefined
test('get name', () => {
  mockGetUser.mockReturnValue(undefined);
  const name = getUser(1).name; // TypeError
});
✓ 修复代码
test('get name', () => {
  mockGetUser.mockReturnValue({ name: 'Alice' });
  const name = getUser(1).name; // 'Alice'
});

配置 mock 到返回 properly shaped 对象, 不 undefined.

如何诊断

  • 检查错误 stack trace 到查找哪里 undefined access happens.

  • 验证所有 mocks 返回 properly shaped 对象, 不 undefined.

  • 添加空 检查 or 可选 chaining in code under 测试.

  • Log 值之前属性 access 到 see 什么它 actually 是.

如何修复

  • 配置 mocks 到返回 expected 对象: mockFn.mockReturnValue({ name: 'Alice' }).

  • 添加空/undefined 检查 in code: 如果 (result) { 返回 result.name; }.

  • Use 可选 chaining: result?.name (返回 undefined 相反的 throwing).

  • Fix 测试数据到 包含所有必需属性.

如何预防

  • 总是配置 mocks 到返回 properly shaped 对象.

  • Use TypeScript 到 catch undefined 属性 access at 编译时间.

  • 添加 defensive 检查 for 外部数据那个可能是 undefined.

相关资源

相关课程

  • Mocking

    Using mocks 到 isolate code.

← 返回语言