Firestore.collection(...)。onSnapshot被调用的次数比预期的多
我目前正在围绕针对模拟器运行的firestore代码编写测试(我尚未针对真实事物进行测试),并且快照的调用次数比我预期的要多得多。创建一个单一的“集合”将导致1个“添加”和2个“修改”,而第二个“集合”将修改数据将导致3个“修改的”文档更改。
这可能是设计使然,但我无法弄清楚为什么会这样。我希望每个更改最多2个修改。 1,具有hasPendingWrites:true,1具有hasPendingWrites:false。
监听一段数据的代码片段:
firestore.collection(teamWsPath).onSnapshot((snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === "added") {
console.log('added');
console.log(change.doc.metadata);
onAdded(change.doc.data() as UserWorkspace);
} else if (change.type === "removed") {
onRemoved(change.doc.data() as UserWorkspace);
} else if (change.type === "modified") {
console.log('modified');
console.log(change.doc.metadata);
onModified(change.doc.data() as UserWorkspace);
}
})
创建/保存Firestore对象,然后再次保存它的测试代码。
it.only('listenToAllTeamWorkspaces should call onModified when a ws is modified', async () => {
const wsData: FSWorkspaceData = new FSWorkspaceData(testDataAPI.getFirestore(), testDataAPI);
let addedCount: number = 0;
let removedCount: number = 0;
let modifiedCount: number = 0;
await wsData.listenToAllTeamWorkspaces(UserWorkspaceTestData.ws1.parentTeamId,
(ws: UserWorkspace) => {
addedCount++;
expect(ws.name).to.equal(UserWorkspaceTestData.ws1.name);
},
(ws) => {
removedCount++;
expect.fail("Nothing should have been removed.")
},
(ws) => {
modifiedCount++;
expect(ws.name).to.equal(UserWorkspaceTestData.ws1.name);
});
await sleep(6000);
console.log("--------------Create Workspace-----------");
await wsData.saveTeamWorkspace(UserWorkspaceTestData.ws1);
await sleep(6000);
//Modified
console.log("--------------Modify Workspace-----------");
UserWorkspaceTestData.ws1.name = "Modified";
await wsData.saveTeamWorkspace(UserWorkspaceTestData.ws1);
await sleep(6000);
expect(addedCount).to.equal(1);
expect(modifiedCount).to.equal(4); //Modified called on 1. Create local, 2. Create remote, 3. Modified Local 4. modified remote
wsData.stopListeningToTeamWorkspaces(UserWorkspaceTestData.ws1.parentTeamId);
});
它产生输出:
--------------Create Workspace-----------
added
SnapshotMetadata { hasPendingWrites: true, fromCache: false }
modified
SnapshotMetadata { hasPendingWrites: true, fromCache: false }
modified
SnapshotMetadata { hasPendingWrites: false, fromCache: false }
--------------Modify Workspace-----------
modified
SnapshotMetadata { hasPendingWrites: true, fromCache: false }
modified
SnapshotMetadata { hasPendingWrites: true, fromCache: false }
modified
SnapshotMetadata { hasPendingWrites: false, fromCache: false }