|
| 1 | +import { setValueByPath, getValueByPath, splitPath } from '../src/utils/getters-setters'; |
| 2 | + |
| 3 | +test('splitPath should split path strings into hierarchical components', () => { |
| 4 | + expect(splitPath('a.b.0.c')).toStrictEqual([ |
| 5 | + { path: 'a' }, |
| 6 | + { path: 'b', couldBeAnArray: true }, |
| 7 | + { path: '0' }, |
| 8 | + { path: 'c' }, |
| 9 | + ]); |
| 10 | + expect(splitPath('a.b[0].c.d')).toStrictEqual([ |
| 11 | + { path: 'a' }, |
| 12 | + { path: 'b', couldBeAnArray: true }, |
| 13 | + { path: '0' }, |
| 14 | + { path: 'c' }, |
| 15 | + { path: 'd' }, |
| 16 | + ]); |
| 17 | + expect(splitPath('a[0].b[2].c[3].d')).toStrictEqual([ |
| 18 | + { path: 'a', couldBeAnArray: true }, |
| 19 | + { path: '0' }, |
| 20 | + { path: 'b', couldBeAnArray: true }, |
| 21 | + { path: '2' }, |
| 22 | + { path: 'c', couldBeAnArray: true }, |
| 23 | + { path: '3' }, |
| 24 | + { path: 'd' }, |
| 25 | + ]); |
| 26 | +}); |
| 27 | + |
| 28 | +test('setValueByPath should set values inside complex objects', () => { |
| 29 | + expect(setValueByPath({}, 'a', 4)).toStrictEqual({ a: 4 }); |
| 30 | + expect(setValueByPath({}, 'a.b', 5)).toStrictEqual({ a: { b: 5 } }); |
| 31 | + expect(setValueByPath({}, 'a[0]', 6)).toStrictEqual({ a: [6] }); |
| 32 | + expect(setValueByPath({ a: {} }, 'a[0]', 6)).toStrictEqual({ a: { '0': 6 } }); |
| 33 | + expect(setValueByPath({}, 'a[0].b', 6)).toStrictEqual({ a: [{ b: 6 }] }); |
| 34 | + expect(setValueByPath({}, '[1]', 'abc')).toStrictEqual({ '1': 'abc' }); |
| 35 | + // eslint-disable-next-line no-sparse-arrays |
| 36 | + expect(setValueByPath(null, '[1]', 'abc')).toStrictEqual([, 'abc']); |
| 37 | +}); |
| 38 | + |
| 39 | +test('getValueByPath should get path value of complex objects', () => { |
| 40 | + expect(getValueByPath({}, 'a')).toBe(undefined); |
| 41 | + expect(getValueByPath({}, '[0]')).toBe(undefined); |
| 42 | + expect(getValueByPath([1, 'h'], '[1]')).toBe('h'); |
| 43 | + expect(getValueByPath([{ a: 'h' }], '[0].a')).toBe('h'); |
| 44 | + expect(getValueByPath({}, 'a.b')).toBe(undefined); |
| 45 | + expect(getValueByPath({ a: [6] }, 'a[0]')).toBe(6); |
| 46 | + expect(getValueByPath({ a: { '0': 6 } }, 'a[0]')).toBe(6); |
| 47 | + expect(getValueByPath({ a: [2, { b: [3, 4, 5, { c: { d: 'efg' } }] }] }, 'a[1].b.3.c')).toStrictEqual({ d: 'efg' }); |
| 48 | +}); |
0 commit comments