Skip to content

Cannot Read Property of Undefined

Error message

                TypeError: Cannot read properties of undefined (reading 'name')
              

Quick summary

The code or test tries to access a property on an undefined value. A mock might not be configured to return the expected object.

Why this happens

  • A mock function returns undefined instead of the expected object.

  • The code under test doesn't handle null/undefined returns from dependencies.

  • Test data is incomplete — missing nested properties.

  • An async operation returned undefined instead of data.

Minimal example

✗ Broken code
const mockGetUser = jest.fn(); // returns undefined
test('get name', () => {
  mockGetUser.mockReturnValue(undefined);
  const name = getUser(1).name; // TypeError
});
✓ Fixed code
test('get name', () => {
  mockGetUser.mockReturnValue({ name: 'Alice' });
  const name = getUser(1).name; // 'Alice'
});

Configure the mock to return a properly shaped object, not undefined.

How to diagnose

  • Check the error stack trace to find where the undefined access happens.

  • Verify all mocks return properly shaped objects, not undefined.

  • Add null checks or optional chaining in the code under test.

  • Log the value before the property access to see what it actually is.

How to fix

  • Configure mocks to return the expected object: mockFn.mockReturnValue({ name: 'Alice' }).

  • Add null/undefined checks in the code: if (result) { return result.name; }.

  • Use optional chaining: result?.name (returns undefined instead of throwing).

  • Fix test data to include all required properties.

How to prevent

  • Always configure mocks to return properly shaped objects.

  • Use TypeScript to catch undefined property access at compile time.

  • Add defensive checks for external data that might be undefined.

Related Resources

Related Lessons

  • Mocking

    Using mocks to isolate code.

← Back to language