Skip to content

Commit

Permalink
Retain object reference if plain when being converted
Browse files Browse the repository at this point in the history
Fix tests
  • Loading branch information
wangyiz4262 committed Sep 20, 2018
1 parent 54b3298 commit 125e5b7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
4 changes: 4 additions & 0 deletions src/api/tojs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,12 @@ function toJSHelper(source, options: ToJSOptions, __alreadySeen: Map<any, any>)

if (isObservableValue(source)) return toJSHelper(source.get(), options!, __alreadySeen)

// Directly return the Date object itself if contained in the observable
if (source instanceof Date) return source

// Fallback to situation if source is an ObservableObject or a plain object
const res = cache(__alreadySeen, source, {}, options)
Object.setPrototypeOf(res, Object.getPrototypeOf(source))
for (let key in source) {
res[key] = toJSHelper(source[key], options!, __alreadySeen)
}
Expand Down
14 changes: 8 additions & 6 deletions test/base/tojs.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ test("json2", function() {
url: "booking.com"
}
})
expect(JSON.parse(JSON.stringify(o))).toEqual({
expect(mobx.toJS(o)).toEqual({
todos: [
{
title: "write blog",
Expand Down Expand Up @@ -217,8 +217,8 @@ test("toJS handles dates", () => {
})

var b = mobx.toJS(a)
expect(b.d instanceof Date).toBe(true)
expect(a.d === b.d).toBe(true)
expect(b.d).toBeInstanceOf(Date)
expect(a.d).toEqual(b.d)
})

test("json cycles", function() {
Expand Down Expand Up @@ -298,9 +298,11 @@ test("verify #566 solution", () => {
const b = mobx.observable({ x: 3 })
const c = mobx.observable({ a: a, b: b })

expect(mobx.toJS(c).a === a).toBeTruthy() // true
expect(mobx.toJS(c).b !== b).toBeTruthy() // false, cloned
expect(mobx.toJS(c).b.x === b.x).toBeTruthy() // true, both 3
expect(mobx.toJS(c).a).toEqual(a)
expect(mobx.toJS(c).a).toBeInstanceOf(MyClass)
expect(mobx.isObservableObject(c.b)).toBeTruthy()
expect(mobx.isObservableObject(mobx.toJS(c).b)).toBeFalsy()
expect(mobx.toJS(c).b).toEqual(mobx.toJS(c.b))
})

test("verify already seen", () => {
Expand Down

0 comments on commit 125e5b7

Please sign in to comment.