File tree Expand file tree Collapse file tree 2 files changed +72
-3
lines changed Expand file tree Collapse file tree 2 files changed +72
-3
lines changed Original file line number Diff line number Diff line change
1
+ import { deepFreeze } from './deepFreeze' ;
2
+
3
+ describe ( 'deepFreeze' , ( ) => {
4
+ it ( 'should deeply freeze an object' , ( ) => {
5
+ const obj = {
6
+ a : 1 ,
7
+ b : {
8
+ c : 2 ,
9
+ d : {
10
+ e : 3 ,
11
+ } ,
12
+ } ,
13
+ } ;
14
+
15
+ const frozenObj = deepFreeze ( obj ) ;
16
+
17
+ expect ( Object . isFrozen ( frozenObj ) ) . toBe ( true ) ;
18
+ expect ( Object . isFrozen ( frozenObj . b ) ) . toBe ( true ) ;
19
+ expect ( Object . isFrozen ( frozenObj . b . d ) ) . toBe ( true ) ;
20
+ } ) ;
21
+
22
+ it ( 'should not allow modification of a deeply frozen object' , ( ) => {
23
+ const obj = {
24
+ a : 1 ,
25
+ b : {
26
+ c : 2 ,
27
+ d : {
28
+ e : 3 ,
29
+ } ,
30
+ } ,
31
+ } ;
32
+
33
+ const frozenObj = deepFreeze ( obj ) ;
34
+
35
+ expect ( ( ) => {
36
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
37
+ // @ts -ignore
38
+ frozenObj . a = 2 ;
39
+ } ) . toThrow ( TypeError ) ;
40
+
41
+ expect ( ( ) => {
42
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
43
+ // @ts -ignore
44
+ frozenObj . b . c = 3 ;
45
+ } ) . toThrow ( TypeError ) ;
46
+
47
+ expect ( ( ) => {
48
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
49
+ // @ts -ignore
50
+ frozenObj . b . d . e = 4 ;
51
+ } ) . toThrow ( TypeError ) ;
52
+ } ) ;
53
+
54
+ it ( 'should return the same object reference' , ( ) => {
55
+ const obj = {
56
+ a : 1 ,
57
+ b : {
58
+ c : 2 ,
59
+ d : {
60
+ e : 3 ,
61
+ } ,
62
+ } ,
63
+ } ;
64
+
65
+ const frozenObj = deepFreeze ( obj ) ;
66
+
67
+ expect ( frozenObj ) . toBe ( obj ) ;
68
+ } ) ;
69
+ } ) ;
Original file line number Diff line number Diff line change 1
- export function deepFreeze < T extends { [ key : string ] : any } > (
1
+ export const deepFreeze = < T extends { [ key : string ] : any } > (
2
2
object : T ,
3
- ) : Readonly < T > {
3
+ ) : Readonly < T > => {
4
4
const propNames = Object . getOwnPropertyNames ( object ) ;
5
5
6
6
for ( const name of propNames ) {
@@ -13,4 +13,4 @@ export function deepFreeze<T extends { [key: string]: any }>(
13
13
}
14
14
15
15
return Object . freeze ( object ) ;
16
- }
16
+ } ;
You can’t perform that action at this time.
0 commit comments