diff --git a/src/utils/helpers.ts b/src/utils/helpers.ts index 6a19a4c..902a341 100644 --- a/src/utils/helpers.ts +++ b/src/utils/helpers.ts @@ -2,7 +2,7 @@ export function deepFreeze(obj: T): void { const propNames = Object.getOwnPropertyNames(obj); for (const name of propNames) { const value = obj[name as keyof T]; - if (typeof value === 'object') { + if (typeof value === 'object' && value !== null) { deepFreeze(value); } } diff --git a/tests/helpers.spec.ts b/tests/helpers.spec.ts new file mode 100644 index 0000000..a409ffb --- /dev/null +++ b/tests/helpers.spec.ts @@ -0,0 +1,43 @@ +import 'jest-extended'; +import { deepFreeze } from '../src/utils/helpers'; + +describe('helpers', () => { + describe('#deepFreeze', () => { + it('should return frozen object', () => { + const data = { + name: 'I am parent', + child: { + name: 'I am child', + }, + }; + + deepFreeze(data); + expect(data).toBeFrozen(); + }); + + it('should freeze the input object that include null valued property without error', () => { + const data = { + name: null, + child: { + name: 'i am child', + }, + }; + + deepFreeze(data); + expect(data).toBeFrozen(); + }); + + it('should freeze the input object include nested property', () => { + const data = { + name: 'I am parent', + child: { + name: 'I am child', + }, + }; + + deepFreeze(data); + const child = data.child; + expect(child).toBeFrozen(); + }); + }); +});