freshyo/apps/user-ui/tests/lib/query-invalidation-keys.test.tsx
2026-09-26 22:29:54 +05:30

55 lines
2.2 KiB
TypeScript

/**
* Query-key shape — why `invalidateQueries({ queryKey: ['a.b.c'] })` silently does nothing.
*
* tRPC v11 stores keys as `[pathArray, { input?, type? }]` (see getQueryKeyInternal in
* @trpc/react-query). TanStack matches a filter against the stored key with partialMatchKey,
* which rejects a string where the key has an array — so the dotted form matches zero queries
* and the mutation's data stays stale.
*
* This is the regression guard for that class: CheckoutAddressSelector was invalidating
* `['user.address.getUserAddresses']` and never refreshing the addresses it renders.
*
* The assertions use getQueryCache().findAll(), which runs the same matcher invalidateQueries
* uses, so no network round trip is involved.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Text } from 'react-native'
import { screen, waitFor } from '@testing-library/react-native'
import { trpc } from '@/src/trpc-client'
import { setupApiMocks } from '../mocks/api'
import { createQueryClient, renderWithProviders } from '../helpers/render'
const PROCEDURE = 'user.address.getUserAddresses'
const Probe = () => {
const q = trpc.user.address.getUserAddresses.useQuery()
return <Text testID="state">{q.isSuccess ? 'ok' : 'pending'}</Text>
}
describe('query key shape', () => {
it('matches the array path form and ignores the dotted string form', async () => {
setupApiMocks({ procedures: { [PROCEDURE]: { data: [] } } })
const client = createQueryClient()
renderWithProviders(<Probe />, { centralStores: false, queryClient: client })
await waitFor(() => expect(screen.getByTestId('state')).toHaveTextContent('ok'))
// The key tRPC really produced for this hook.
const stored = client.getQueryCache().getAll()[0]
expect(stored.queryKey[0]).toEqual(['user', 'address', 'getUserAddresses'])
// The old, dotted form: matches nothing, so the invalidation was a no-op.
expect(
client.getQueryCache().findAll({ queryKey: ['user.address.getUserAddresses'] })
).toHaveLength(0)
// The form tRPC's own utils.X.invalidate() builds: matches.
expect(
client.getQueryCache().findAll({ queryKey: [['user', 'address', 'getUserAddresses']] })
).toHaveLength(1)
})
})