Skip to content

Symbol properties inside objects passed to the build function as associations are not getting merged into result #105

Description

@asla3

Description

If you call a factory's build function passing an object that contains symbols as properties, the symbols props won't be merged into the build result as seen here:

type User = {
  name: string;
};

type Post = {
  name: string;
  user: User;
};

const userFactory = Factory.define<User>(() => ({
  name: "Susan"
}));

const postFactory = Factory.define<Post>(() => ({
    name: "Post 1",
    user: userFactory.build()
  }));

const sym = Symbol("a");

const userWithSymbol = { ...userFactory.build(), [sym]: "a" };

const postFactoryResult = postFactory.build(
    {},
    { associations: { user: userWithSymbol } }
);

console.log(postFactoryResult.user[sym]) // it should return "a" but it's returning undefined instead because user doesn't have the symbol prop.

To Reproduce

I made this sandbox that showcases this behavior: https://codesandbox.io/s/fishery-test-forked-30eett?file=/src/index.test.ts

Additional context
After peaking around for a bit, I found out that this happens because the mergeCustomizer used in this library doesn't handle symbols, so it relies on lodash.merge behaviour which doesn't merge symbols by default as seen in this issue. For now, I found this workaround that does merge symbols into the resulting object:

const postFactory = Factory.define<Post>(({associations}) => ({
    name: "Post 1",
    user: associations.user || userFactory.build()
  }));

My guess is that it works because user gets the same object we passed that already has the symbols present on it, so when fishery starts merging our factory's return value with associations and params it doesn't remove the symbols that are already present on user.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions