-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimmutability-helper.spec.ts
119 lines (102 loc) · 2.84 KB
/
immutability-helper.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import update from 'immutability-helper'
// https://github.com/kolodny/immutability-helper
describe('immutability helper', () => {
describe('object', () => {
test('replace obj key value', () => {
const obj = {
a: 1,
b: {
c: {
d: 2
}
}
}
const obj2 = update(obj, {
b: {
c: {
d: {
$set: 3
}
}
}
})
expect(obj2).toEqual({
a: 1,
b: {
c: {
d: 3
}
}
})
})
test('update obj key value', () => {
const obj = {
a: 1,
b: 2,
c: 3
}
const obj2 = update(obj, {
$merge: {
b: 6,
c: 8
}
})
expect(obj2).toEqual({
a: 1,
b: 6,
c: 8
})
})
test('merge attr into obj', () => {
const obj = {a: 1, b: 2}
const obj2 = update(obj, {
$merge: {
c: 3,
d: 4
} as any
})
expect(obj2).toEqual({
a: 1,
b: 2,
c: 3,
d: 4
})
})
})
describe('array', () => {
test('array add item', () => {
const arr = [1, 2]
let arrPushed = update(arr, {
$push: [3]
})
expect(arrPushed).toEqual([1, 2, 3])
arrPushed = update(arr, {
$push: [5, 6]
})
expect(arrPushed).toEqual([1, 2, 5, 6])
const arrUnshift = update(arr, {
$unshift: [3]
})
expect(arrUnshift).toEqual([3, 1, 2])
// 和数组的 splice 一样
const arrInsertIndex = update(arr, {
$splice: [[1, 0, 100, 200]] // [[插入位置,删除格式,插入值...]]
})
expect(arrInsertIndex).toEqual([1, 100, 200, 2])
})
test('array remove item', () => {
const arr = [1, 2, 3, 4, 5]
let arrPushed = update(arr, {
$splice: [[1, 3]]
})
expect(arrPushed).toEqual([1, 5])
})
test('replace item', () => {
const arr = [1, 2, 3, 4, 5]
let replacedArr = update(arr, {
$splice: [[1, 1, 100]]
})
expect(replacedArr).toEqual([1, 100, 3, 4, 5])
})
})
})