dot-prop-immutable icon indicating copy to clipboard operation
dot-prop-immutable copied to clipboard

Unexpected behavior when an intermediate key is `null`

Open sturench opened this issue 7 years ago • 2 comments

When attempting to access a a nested attribute of a null value, a TypeError is encountered.

The below test suite illustrates the behavior.

Is this intended, or something that can/should be handled in the library?

describe('dot-prop-immutable get behavior', () => {
  const testObject = {
    a: {
      b: {
        c: 1
      },
      nullKey: null
    }
  };
  it('returns correct value when all keys present', () => {
    expect(dotProp.get(testObject, 'a.b.c')).toBe(1);
  });

  it('returns undefined when an intermediate key is missing', () => {
    expect(dotProp.get(testObject, 'a.missingKey.c')).toBeUndefined();
  });

  it('returns null when a leaf key is null', () => {
    expect(dotProp.get(testObject, 'a.nullKey')).toBeNull();
  });

  it('returns undefined when an intermediate key is missing', () => {
    expect(dotProp.get(testObject, 'a.missingKey.c')).toBeUndefined();
  });

  // This test currently fails.  My expectation is that it would return
  // undefined.
  it('returns undefined when an intermediate key is null', () => {
    expect(dotProp.get(testObject, 'a.nullKey.anotherKey')).toBeUndefined();
  });
});
 FAIL  src/__test__/utils.test.js
  ● dot-prop-immutable get behavior › returns undefined when an intermediate key is null

    TypeError: Cannot read property 'anotherKey' of null

      at Object.get (node_modules/dot-prop-immutable/index.js:48:13)
      at Object.it (src/__test__/utils.test.js:206:39)
          at Promise (<anonymous>)
      at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
          at <anonymous>
      at process._tickCallback (internal/process/next_tick.js:188:7)
  dot-prop-immutable get behavior
    ✓ returns correct value when all keys present
    ✓ returns undefined when an intermediate key is missing (1ms)
    ✓ returns null when a leaf key is null
    ✓ returns undefined when an intermediate key is missing
    ✕ returns undefined when an intermediate key is null

Test Suites: 1 failed, 1 total

sturench avatar Dec 07 '17 17:12 sturench

Hi,

sorry for the late response to this.

This issue should be resolved with these changes published in latest version: https://github.com/debitoor/dot-prop-immutable/pull/23

hilleer avatar Jan 08 '20 14:01 hilleer

This still happens when there is a call to set with an intermediate key that is null, e.g. dotProp.set(testObject, 'a.nullKey.anotherKey', 'a value')

ghost avatar Oct 09 '20 02:10 ghost