Skip to content

Commit

Permalink
Merge pull request #842 from SirbyAlive/634-fix-undefined-optional-fr…
Browse files Browse the repository at this point in the history
…ozen-to-default-value

#634 fix optional frozen to return default value if undefined
  • Loading branch information
mweststrate authored Jun 8, 2018
2 parents 72989a4 + 6174918 commit 5993c6c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class OptionalValue<S, T> extends Type<S, T> {
reconcile(current: INode, newValue: any): INode {
return this.type.reconcile(
current,
this.type.is(newValue) ? newValue : this.getDefaultValue()
this.type.is(newValue) && newValue !== undefined ? newValue : this.getDefaultValue()
)
}

Expand Down
20 changes: 18 additions & 2 deletions packages/mobx-state-tree/test/optional.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getSnapshot, types, unprotect } from "../src"
import { getSnapshot, types, unprotect, applySnapshot } from "../src"
test("it should provide a default value, if no snapshot is provided", () => {
const Row = types.model({
name: "",
Expand Down Expand Up @@ -66,7 +66,8 @@ test("Values should reset to default if omitted in snapshot", () => {
todo: types.model({
id: types.identifier(),
done: false,
title: "test"
title: "test",
thing: types.optional(types.frozen, {})
})
})
const store = Store.create({ todo: { id: "2" } })
Expand All @@ -77,6 +78,21 @@ test("Values should reset to default if omitted in snapshot", () => {
expect(store.todo.title).toBe("stuff")
expect(store.todo.done).toBe(false)
})

test("optional frozen should fallback to default value if snapshot is undefined", () => {
const Store = types.model({
thing: types.optional(types.frozen, {})
})
const store = Store.create({
thing: null
})

expect(store.thing).toBeNull()
applySnapshot(store, {})
expect(store.thing).toBeDefined()
expect(store.thing).toEqual({})
})

test("a model is a valid default value, snapshot will be used", () => {
const Row = types.model({
name: "",
Expand Down

0 comments on commit 5993c6c

Please sign in to comment.