Skip to content

Commit d90fefa

Browse files
Merge pull request cerebral#244 from lrn2prgrm/patch-3
Fix deepCopy to pass getters to cloned object
2 parents 6eea3fc + 1b65674 commit d90fefa

File tree

3 files changed

+49
-3
lines changed

3 files changed

+49
-3
lines changed

packages/node_modules/overmind/src/index.test.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { EventType, Overmind, IAction } from './'
1+
import { EventType, Overmind, IAction, createOvermindMock } from './'
22
import { namespaced } from './config'
33

44
function toJSON(obj) {
@@ -332,3 +332,23 @@ describe('Overmind', () => {
332332
expect(app.state.item.isAwesome).toBe(false)
333333
})
334334
})
335+
336+
describe('Overmind mock', () => {
337+
test('should preserve getters', async (done) => {
338+
expect.assertions(1)
339+
const state = {
340+
value: 0,
341+
get valuePlusTwo() { return this.value + 2 }
342+
}
343+
const updateValue: Action = (context) => context.state.value = 15
344+
const actions = { updateValue }
345+
const config = { state, actions}
346+
type Config = typeof config
347+
interface Action<Value = void> extends IAction<Config, Value> {}
348+
349+
const mock = createOvermindMock(config)
350+
await mock.actions.updateValue()
351+
expect(mock.state.valuePlusTwo).toEqual(17)
352+
done()
353+
})
354+
})
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { deepCopy } from './utils'
2+
3+
describe('deepCopy', () => {
4+
test('should be able to preserve getters', () => {
5+
expect.assertions(1)
6+
const original = {
7+
value: 0,
8+
get valuePlusTwo() { return this.value + 2 }
9+
}
10+
const copy = deepCopy(original)
11+
copy.value = 15
12+
expect(copy.valuePlusTwo).toBe(17)
13+
})
14+
})

packages/node_modules/overmind/src/utils.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,20 @@ export const makeStringifySafeMutations = (mutations: IMutation[]) => {
2929

3030
export function deepCopy(obj) {
3131
if (isPlainObject(obj)) {
32-
return Object.keys(obj).reduce((aggr, key) => {
33-
aggr[key] = deepCopy(obj[key])
32+
return Object.keys(obj).reduce((aggr: any, key) => {
33+
if (key === '__esModule') {
34+
return aggr
35+
}
36+
37+
const originalDescriptor = Object.getOwnPropertyDescriptor(obj, key)
38+
const isAGetter = originalDescriptor && 'get' in originalDescriptor
39+
const value = obj[key]
40+
41+
if (isPlainObject(value) && !isAGetter) {
42+
aggr[key] = deepCopy(value)
43+
} else {
44+
Object.defineProperty(aggr, key, originalDescriptor as any)
45+
}
3446

3547
return aggr
3648
}, {})

0 commit comments

Comments
 (0)