Skip to content

Commit

Permalink
fix(helpers): improve deepMergeObject handling case (#62)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
Tahul and antfu authored May 24, 2023
1 parent e916e98 commit fb50fb1
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/helpers/deep-merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import type { Proxified } from "../types";
export function deepMergeObject(magicast: Proxified<any>, object: any) {
if (typeof object === "object") {
for (const key in object) {
if (typeof object[key] === "object") {
if (
typeof magicast[key] === "object" &&
typeof object[key] === "object"
) {
deepMergeObject(magicast[key], object[key]);
} else {
magicast[key] = object[key];
Expand Down
76 changes: 76 additions & 0 deletions test/object.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { parseModule } from "../src";
import { deepMergeObject } from "../src/helpers/deep-merge";
import { generate } from "./_utils";

describe("object", () => {
Expand Down Expand Up @@ -50,4 +51,79 @@ export default {
};"
`);
});

it("recursively create objects", () => {
const mod = parseModule(
`
export default {
foo: {
}
}
`.trim()
);

// Update existing object keys
expect(mod.exports.default.foo).toEqual({});
mod.exports.default.foo.value = 1;
expect(mod.exports.default.foo.value).toEqual(1);

// Create nested object
mod.exports.default.bar = {};
mod.exports.default.bar.testValue = {};
mod.exports.default.bar.testValue.value = "a";

expect(generate(mod)).toMatchInlineSnapshot(`
"export default {
foo: {
value: 1,
},
bar: {
testValue: {
value: \\"a\\",
},
},
};"
`);
});

it("recursively merge objects", () => {
const mod = parseModule(
`
export default {
foo: {
}
}
`.trim()
);

const obj = {
foo: {
value: 1,
},

bar: {
testValue: {
value: "a",
},
},
};

// Recursively merge existing object with `obj`
deepMergeObject(mod.exports.default, obj);

expect(generate(mod)).toMatchInlineSnapshot(`
"export default {
foo: {
value: 1,
},
bar: {
testValue: {
value: \\"a\\",
},
},
};"
`);
});
});

0 comments on commit fb50fb1

Please sign in to comment.