|
| 1 | +describe('get_own', () => { |
| 2 | + describe.each([ |
| 3 | + [ |
| 4 | + 'when Object.hasOwn is available', |
| 5 | + function beforeAllFn() { |
| 6 | + // clear require cache before running tests as the implementation of |
| 7 | + // hasOwn depends on whether Object.hasOwn is available |
| 8 | + jest.resetModules(); |
| 9 | + expect(Object.hasOwn).toBeInstanceOf(Function); |
| 10 | + }, |
| 11 | + ], |
| 12 | + [ |
| 13 | + 'when Object.hasOwn is not available', |
| 14 | + function beforeAllFn() { |
| 15 | + jest.resetModules(); |
| 16 | + delete Object.hasOwn; |
| 17 | + expect(Object.hasOwn).toBeUndefined(); |
| 18 | + }, |
| 19 | + ], |
| 20 | + ])('unit tests %s', (_, beforeAllFn) => { |
| 21 | + let getOwn: typeof import('./get_own').getOwn; |
| 22 | + |
| 23 | + beforeAll(async () => { |
| 24 | + beforeAllFn(); |
| 25 | + |
| 26 | + const res = await import('./get_own'); |
| 27 | + getOwn = res.getOwn; |
| 28 | + }); |
| 29 | + |
| 30 | + afterEach(() => { |
| 31 | + jest.resetModules(); |
| 32 | + }); |
| 33 | + |
| 34 | + test('returns value for own properties', () => { |
| 35 | + const obj = {key: 'value'}; |
| 36 | + expect(getOwn(obj, 'key')).toBe('value'); |
| 37 | + }); |
| 38 | + |
| 39 | + test('returns value for falsy own properties', () => { |
| 40 | + const obj = {key: false, key2: 0, key3: '', key4: undefined, key5: null}; |
| 41 | + expect(getOwn(obj, 'key')).toBe(false); |
| 42 | + expect(getOwn(obj, 'key2')).toBe(0); |
| 43 | + expect(getOwn(obj, 'key3')).toBe(''); |
| 44 | + expect(getOwn(obj, 'key4')).toBeUndefined(); |
| 45 | + expect(getOwn(obj, 'key5')).toBeNull(); |
| 46 | + }); |
| 47 | + |
| 48 | + test('returns undefined for properties inherited from the prototype', () => { |
| 49 | + const obj = {key: 'value'}; |
| 50 | + expect(getOwn(obj, '__proto__')).toBeUndefined(); |
| 51 | + expect(getOwn(obj, 'constructor')).toBeUndefined(); |
| 52 | + expect(getOwn(obj, 'valueOf')).toBeUndefined(); |
| 53 | + |
| 54 | + const inheritedKey = 'inheritedKey'; |
| 55 | + const prototype = {[inheritedKey]: 1234}; |
| 56 | + const objWithPrototype = Object.create(prototype); |
| 57 | + expect(getOwn(objWithPrototype, inheritedKey)).toBeUndefined(); |
| 58 | + }); |
| 59 | + |
| 60 | + test('returns true for own properties that have the same name as a property in the prototype', () => { |
| 61 | + const obj = JSON.parse('{"__proto__": 123, "valueOf": "123"}'); |
| 62 | + expect(getOwn(obj, '__proto__')).toBe(123); |
| 63 | + expect(getOwn(obj, 'valueOf')).toBe('123'); |
| 64 | + }); |
| 65 | + }); |
| 66 | +}); |
0 commit comments