Skip to content

set without merge overrides _collections #170

@arv

Description

@arv

Description

When there are nested collections set does not work as expected.

Steps to reproduce

function fakeFirestore() {
  return firebaseStub(
    {database: {}},
    {mutable: true},
  ).firestore();
}


test('Setting collections conflicts', async () => {
  const firestore = fakeFirestore();

  await firestore.doc('teams/teamID/users/userID').set({name: 'User Name'});
  await firestore.doc('teams/teamID').set({name: 'Team Name'});

  expect((await firestore.doc('teams/teamID').get()).data()).toEqual({
    name: 'Team Name',
  });

  expect(
    (await firestore.doc('teams/teamID/users/userID').get()).data(),
  ).toEqual({
    name: 'User Name',
  });
});

The problem is that the second set does not propagate the _collections.

Expected result

The _collections property should be maintained and a set should not drop sub collections.

Actual result

The teams/teamID/users/userID doc is lost

Environment

  • Node version:

v18.16.0

Potential fix:

https://github.com/Upstatement/firestore-jest-mock/blob/f2158d050d3c334c049ed49b68c6849f90c0fa56/mocks/firestore.js#L217-L224

    // parent should now be an array of documents
    // Replace existing data, if it's there, or add to the end of the array
    const oldIndex = parent.findIndex(doc => doc.id === docId);
    const newIndex = oldIndex >= 0 ? oldIndex : parent.length;
    const newValue = {
      ...(merge ? parent[oldIndex] : undefined),
      ...object,
      id: docId,
    };
    const oldValue = parent[newIndex];
    if (oldValue?._collections) {
      newValue._collections = oldValue._collections;
    }
    parent[newIndex] = newValue;

The above can be written more concise with ... and ?. and ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions