|
| 1 | +import get from './get'; |
| 2 | + |
| 3 | +describe('get', () => { |
| 4 | + const deepObject = { |
| 5 | + a: { b: { c: 'c' } }, |
| 6 | + falseVal: false, |
| 7 | + nullVal: null, |
| 8 | + undefinedVal: undefined, |
| 9 | + arrayVal: ['arr'], |
| 10 | + }; |
| 11 | + |
| 12 | + test('takes a path and an object and returns the value at the path or the default value', () => { |
| 13 | + const obj = { |
| 14 | + a: { |
| 15 | + b: { |
| 16 | + c: 100, |
| 17 | + d: 200, |
| 18 | + }, |
| 19 | + e: { |
| 20 | + f: [100, 101, 102], |
| 21 | + g: 'G', |
| 22 | + }, |
| 23 | + h: 'H', |
| 24 | + }, |
| 25 | + i: 'I', |
| 26 | + j: ['J'], |
| 27 | + }; |
| 28 | + |
| 29 | + expect(get(obj, ['a', 'b', 'c'], 'Unknown')).toBe(100); |
| 30 | + expect(get(obj, [], 'Unknown')).toBe(obj); |
| 31 | + expect(get(obj, ['a', 'e', 'f', 1], 'Unknown')).toBe(101); |
| 32 | + expect(get(obj, ['j', 0], 'Unknown')).toBe('J'); |
| 33 | + expect(get(obj, ['j', 1], 'Unknown')).toBe('Unknown'); |
| 34 | + expect(get(null, ['a', 'b', 'c'], 'Unknown')).toBe('Unknown'); |
| 35 | + }); |
| 36 | + |
| 37 | + test("gets a deep property's value from objects", () => { |
| 38 | + expect(get(deepObject, ['a', 'b', 'c'], 'Unknown')).toBe('c'); |
| 39 | + expect(get(deepObject, ['a'], 'Unknown')).toBe(deepObject.a); |
| 40 | + }); |
| 41 | + |
| 42 | + test('returns the default value for items not found', () => { |
| 43 | + expect(get(deepObject, ['a', 'b', 'foo'], 'Unknown')).toBe('Unknown'); |
| 44 | + expect(get(deepObject, ['bar'], 'Unknown')).toBe('Unknown'); |
| 45 | + }); |
| 46 | + |
| 47 | + test('returns the default value for null/undefined', () => { |
| 48 | + expect(get(null, ['toString'], 'Unknown')).toBe('Unknown'); |
| 49 | + expect(get(undefined, ['toString'], 'Unknown')).toBe('Unknown'); |
| 50 | + }); |
| 51 | + |
| 52 | + test('works with falsy items', () => { |
| 53 | + expect(get(false, ['toString'], 'Unknown')).toBe( |
| 54 | + Boolean.prototype.toString, |
| 55 | + ); |
| 56 | + }); |
| 57 | +}); |
0 commit comments