Skip to content

Commit 23a1c3f

Browse files
committed
Harden optimisticUpserts test
1 parent ef84607 commit 23a1c3f

File tree

1 file changed

+22
-15
lines changed

1 file changed

+22
-15
lines changed

packages/toolkit/src/query/tests/optimisticUpserts.test.tsx

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -399,27 +399,34 @@ describe('upsertQueryEntries', () => {
399399
storeRef.store.dispatch(entriesAction)
400400

401401
// Tricky timing. The cache data promises will be resolved
402-
// in microtasks, so we just need any async delay here.
403-
await delay(10)
402+
// in microtasks. We need to wait for them. Best to do this
403+
// in a loop just to avoid a hardcoded delay, but also this
404+
// needs to complete before `keepUnusedDataFor` expires them.
405+
await waitFor(
406+
() => {
407+
const state = storeRef.store.getState()
408+
409+
// onCacheEntryAdded should have run for each post,
410+
// including cache data being resolved
411+
for (const post of posts) {
412+
const matchingSideEffectAction = state.actions.find(
413+
(action) =>
414+
postAddedAction.match(action) && action.payload === post.id,
415+
)
416+
expect(matchingSideEffectAction).toBeTruthy()
417+
}
404418

405-
const state = storeRef.store.getState()
419+
const selectedData =
420+
api.endpoints.postWithSideEffect.select('1')(state).data
406421

407-
// onCacheEntryAdded should have run for each post,
408-
// including cache data being resolved
409-
for (const post of posts) {
410-
const matchingSideEffectAction = state.actions.find(
411-
(action) => postAddedAction.match(action) && action.payload === post.id,
412-
)
413-
expect(matchingSideEffectAction).toBeTruthy()
414-
}
415-
416-
expect(api.endpoints.postWithSideEffect.select('1')(state).data).toBe(
417-
posts[0],
422+
expect(selectedData).toBe(posts[0])
423+
},
424+
{ timeout: 50, interval: 5 },
418425
)
419426

420427
// The cache data should be removed after the keepUnusedDataFor time,
421428
// so wait longer than that
422-
await delay(20)
429+
await delay(100)
423430

424431
const stateAfter = storeRef.store.getState()
425432

0 commit comments

Comments
 (0)