Skip to content

Commit f64c366

Browse files
committed
Fix deepCopy to pass getters to cloned object
The previous implementation would take `{ get x() { return 123 } }` and return `{ x: 123 }` which resulted in problems when I was trying to run tests with createOvermindMock
1 parent b8fcd6b commit f64c366

File tree

3 files changed

+40
-4
lines changed

3 files changed

+40
-4
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: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,11 @@ 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])
34-
32+
return Object.keys(obj).reduce((aggr: any, key) => {
33+
if(obj.__lookupGetter__(key))
34+
aggr.__defineGetter__(key, obj.__lookupGetter__(key))
35+
else
36+
aggr[key] = deepCopy(obj[key])
3537
return aggr
3638
}, {})
3739
} else if (Array.isArray(obj)) {

0 commit comments

Comments
 (0)