diff --git a/__tests__/patch.js b/__tests__/patch.js index 8345ab06..7baba6e5 100644 --- a/__tests__/patch.js +++ b/__tests__/patch.js @@ -1119,3 +1119,31 @@ describe("#588", () => { [{op: "add", path: ["num"], value: 42}] ) }) + +test("#676 patching Date objects", () => { + class Test { + constructor() { + this.test = true + } + perform() { + return "tested!" + } + } + + const [nextState, patches] = produceWithPatches({}, function(draft) { + draft.date = new Date(2020, 10, 10, 8, 8, 8, 3) + draft.test = new Test() + }) + + expect(nextState.date.toJSON()).toMatchInlineSnapshot( + `"2020-11-10T08:08:08.003Z"` + ) + expect(nextState.test.perform()).toBe("tested!") + + const rebuilt = applyPatches({}, patches) + expect(rebuilt.date).toBeInstanceOf(Date) + expect(rebuilt.date.toJSON()).toMatchInlineSnapshot( + `"2020-11-10T08:08:08.003Z"` + ) + expect(rebuilt.date).toEqual(new Date(2020, 10, 10, 8, 8, 8, 3)) +}) diff --git a/src/plugins/patches.ts b/src/plugins/patches.ts index 6470c9d5..998627f2 100644 --- a/src/plugins/patches.ts +++ b/src/plugins/patches.ts @@ -25,7 +25,8 @@ import { ArchtypeSet, ArchtypeArray, die, - isDraft + isDraft, + isDraftable } from "../internal" export function enablePatches() { @@ -267,7 +268,7 @@ export function enablePatches() { // (See failing test when deepClone just returns obj) function deepClonePatchValue(obj: T): T function deepClonePatchValue(obj: any) { - if (!obj || typeof obj !== "object") return obj + if (!isDraftable(obj)) return obj if (Array.isArray(obj)) return obj.map(deepClonePatchValue) if (isMap(obj)) return new Map(