281 lines
8.7 KiB
TypeScript
281 lines
8.7 KiB
TypeScript
/**
|
|
* Mutation → refetch wiring.
|
|
*
|
|
* Each test mounts a real observer of the query the mutation is supposed to
|
|
* refresh, fires the mutation through the UI/hook, and asserts the query is
|
|
* fetched again. This deliberately checks that the invalidation key actually
|
|
* matches an observer — a spy on `invalidateQueries` would still pass for a
|
|
* no-op key like the string `['user.address.getUserAddresses']` (tRPC v11 keys
|
|
* are `[['user','address','getUserAddresses'], {...}]`).
|
|
*/
|
|
|
|
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
|
|
|
|
import React from 'react'
|
|
import { Alert } from 'react-native'
|
|
import { act, fireEvent, renderHook, screen, waitFor } from '@testing-library/react-native'
|
|
|
|
import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent'
|
|
import OrderDetails from '@/app/(drawer)/(tabs)/me/my-orders/[id]'
|
|
import Addresses from '@/app/(drawer)/(tabs)/me/addresses/index'
|
|
import Coupons from '@/app/(drawer)/(tabs)/me/coupons/index'
|
|
import { useUpdateProfile } from '@/src/api-hooks/auth.api'
|
|
import { trpc } from '@/src/trpc-client'
|
|
import { resetStorage, setupApiMocks } from '../mocks/api'
|
|
import { authMock, resetAuthMock } from '../mocks/auth'
|
|
import { procedureCalls } from '../mocks/procedures'
|
|
import { searchParamsMock } from '../mocks/router'
|
|
import { createQueryClient, Providers, renderWithProviders } from '../helpers/render'
|
|
|
|
const USER = {
|
|
id: 5,
|
|
name: 'Test User',
|
|
email: 'test@example.com',
|
|
mobile: '9876543210',
|
|
profileImage: '',
|
|
createdAt: '',
|
|
}
|
|
|
|
const ADDRESS = {
|
|
id: 1,
|
|
name: 'Home',
|
|
phone: '9876543210',
|
|
addressLine1: '12 Main Road',
|
|
addressLine2: 'Apt 4',
|
|
city: 'Hyderabad',
|
|
state: 'Telangana',
|
|
isDefault: false,
|
|
}
|
|
|
|
const ORDER = {
|
|
id: 42,
|
|
orderId: 'ORD-42',
|
|
orderDate: '2026-09-20T10:00:00.000Z',
|
|
createdAt: '2026-09-20T10:00:00.000Z',
|
|
orderStatus: 'confirmed',
|
|
deliveryStatus: 'pending',
|
|
deliveryDate: '2026-09-26T10:00:00.000Z',
|
|
cancelReason: null,
|
|
paymentMode: 'COD',
|
|
paymentStatus: 'pending',
|
|
orderAmount: 500,
|
|
discountAmount: 0,
|
|
deliveryCharge: 15,
|
|
couponCode: null,
|
|
isFlashDelivery: false,
|
|
userNotes: null,
|
|
items: [
|
|
{
|
|
productName: 'Chicken Breast 500 g',
|
|
quantity: 1,
|
|
unitNotation: '500g',
|
|
price: 215,
|
|
amount: 215,
|
|
image: null,
|
|
},
|
|
],
|
|
}
|
|
|
|
const baseProps = {
|
|
selectedAddress: 1,
|
|
selectedSlots: { 1: 1849 },
|
|
selectedCouponIds: [],
|
|
cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }],
|
|
totalPrice: 215,
|
|
totalSavings: 0,
|
|
discountAmount: 0,
|
|
finalTotal: 215,
|
|
finalTotalWithDelivery: 230,
|
|
deliveryCharge: 15,
|
|
constsData: { freeDeliveryThreshold: 249, deliveryCharge: 15 },
|
|
selectedCoupons: [],
|
|
}
|
|
|
|
/** Mounted observers so an invalidation has something to refetch. */
|
|
const OrdersProbe = () => {
|
|
trpc.user.order.getOrders.useQuery({ page: 1, pageSize: 50 })
|
|
return null
|
|
}
|
|
const EligibleProbe = () => {
|
|
trpc.user.coupon.getEligible.useQuery(undefined, { enabled: true })
|
|
return null
|
|
}
|
|
const DefaultAddressProbe = () => {
|
|
trpc.user.address.getDefaultAddress.useQuery()
|
|
return null
|
|
}
|
|
|
|
const count = (api: ReturnType<typeof setupApiMocks>, name: string) =>
|
|
procedureCalls(api.fetchMock, name).length
|
|
|
|
describe('mutation invalidation', () => {
|
|
beforeEach(async () => {
|
|
// Flush a batched tRPC request left over from the previous test.
|
|
await act(async () => {
|
|
jest.advanceTimersByTime(1)
|
|
})
|
|
resetAuthMock()
|
|
await resetStorage()
|
|
searchParamsMock.current = {}
|
|
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
|
|
})
|
|
|
|
it('refetches getOrders after placeOrder, so NextOrderGlimpse updates', async () => {
|
|
const queryClient = createQueryClient()
|
|
const api = setupApiMocks({
|
|
orders: [],
|
|
procedures: { 'user.order.placeOrder': { data: [{ id: 99, isCod: true }] } },
|
|
})
|
|
|
|
renderWithProviders(
|
|
<>
|
|
<PaymentAndOrderComponent {...baseProps} />
|
|
<OrdersProbe />
|
|
</>,
|
|
{ centralStores: false, queryClient }
|
|
)
|
|
|
|
await waitFor(() => expect(count(api, 'user.order.getOrders')).toBeGreaterThan(0))
|
|
const before = count(api, 'user.order.getOrders')
|
|
|
|
fireEvent.press(screen.getByTestId('place-order-button'))
|
|
|
|
await waitFor(() => expect(count(api, 'user.order.getOrders')).toBeGreaterThan(before))
|
|
})
|
|
|
|
it('refetches getOrders after cancelling from the order detail screen', async () => {
|
|
const queryClient = createQueryClient()
|
|
const api = setupApiMocks({
|
|
orders: [],
|
|
procedures: {
|
|
'user.order.getOrderById': ORDER,
|
|
'user.order.cancelOrder': { success: true },
|
|
},
|
|
})
|
|
searchParamsMock.current = { id: String(ORDER.id) }
|
|
|
|
renderWithProviders(
|
|
<>
|
|
<OrderDetails />
|
|
<OrdersProbe />
|
|
</>,
|
|
{ centralStores: false, queryClient }
|
|
)
|
|
|
|
await waitFor(() => expect(screen.getByText('Cancel Order')).toBeVisible())
|
|
await waitFor(() => expect(count(api, 'user.order.getOrders')).toBeGreaterThan(0))
|
|
const before = count(api, 'user.order.getOrders')
|
|
|
|
fireEvent.press(screen.getByText('Cancel Order'))
|
|
await waitFor(() => expect(screen.getByTestId('cancel-reason')).toBeVisible())
|
|
fireEvent.changeText(screen.getByTestId('cancel-reason'), 'Changed my mind')
|
|
fireEvent.press(screen.getByText('Confirm Cancellation'))
|
|
|
|
await waitFor(() => expect(count(api, 'user.order.cancelOrder')).toBeGreaterThan(0))
|
|
await waitFor(() => expect(count(api, 'user.order.getOrders')).toBeGreaterThan(before))
|
|
})
|
|
|
|
it('refetches eligible coupons after redeeming a reserved coupon', async () => {
|
|
const queryClient = createQueryClient()
|
|
const api = setupApiMocks({
|
|
procedures: {
|
|
'user.coupon.getMyCoupons': { data: { personal: [], general: [] } },
|
|
'user.coupon.redeemReservedCoupon': { success: true },
|
|
'user.coupon.getEligible': { data: [] },
|
|
},
|
|
})
|
|
|
|
renderWithProviders(
|
|
<>
|
|
<Coupons />
|
|
<EligibleProbe />
|
|
</>,
|
|
{ queryClient }
|
|
)
|
|
|
|
await waitFor(() => expect(screen.getByText('Add a Coupon')).toBeVisible())
|
|
await waitFor(() => expect(count(api, 'user.coupon.getEligible')).toBeGreaterThan(0))
|
|
const before = count(api, 'user.coupon.getEligible')
|
|
|
|
fireEvent.changeText(screen.getByPlaceholderText('Enter coupon code'), 'secret1')
|
|
fireEvent.press(screen.getByText('Add Coupon'))
|
|
|
|
await waitFor(() =>
|
|
expect(count(api, 'user.coupon.redeemReservedCoupon')).toBeGreaterThan(0)
|
|
)
|
|
await waitFor(() => expect(count(api, 'user.coupon.getEligible')).toBeGreaterThan(before))
|
|
})
|
|
|
|
it('refetches the default address after setting a new default', async () => {
|
|
const queryClient = createQueryClient()
|
|
const api = setupApiMocks({
|
|
procedures: {
|
|
'user.address.getUserAddresses': { data: [ADDRESS] },
|
|
'user.address.updateAddress': { success: true },
|
|
'user.address.getDefaultAddress': { success: true, data: ADDRESS },
|
|
},
|
|
})
|
|
|
|
renderWithProviders(
|
|
<>
|
|
<Addresses />
|
|
<DefaultAddressProbe />
|
|
</>,
|
|
{ queryClient }
|
|
)
|
|
|
|
await waitFor(() => expect(screen.getByText('Set Default')).toBeVisible())
|
|
await waitFor(() =>
|
|
expect(count(api, 'user.address.getDefaultAddress')).toBeGreaterThan(0)
|
|
)
|
|
const before = count(api, 'user.address.getDefaultAddress')
|
|
|
|
fireEvent.press(screen.getByText('Set Default'))
|
|
|
|
await waitFor(() =>
|
|
expect(count(api, 'user.address.updateAddress')).toBeGreaterThan(0)
|
|
)
|
|
await waitFor(() =>
|
|
expect(count(api, 'user.address.getDefaultAddress')).toBeGreaterThan(before)
|
|
)
|
|
})
|
|
|
|
it('refetches getSelfData after updateProfile', async () => {
|
|
const queryClient = createQueryClient()
|
|
const api = setupApiMocks({
|
|
procedures: {
|
|
'user.user.getSelfData': { data: { user: USER } },
|
|
'user.auth.updateProfile': { data: { token: 't', user: USER } },
|
|
},
|
|
})
|
|
authMock.user = { id: USER.id }
|
|
|
|
const { result } = renderHook(
|
|
() => {
|
|
const mutation = useUpdateProfile()
|
|
const query = trpc.user.user.getSelfData.useQuery()
|
|
return { mutation, query }
|
|
},
|
|
{
|
|
wrapper: ({ children }: { children?: React.ReactNode }) => (
|
|
<Providers queryClient={queryClient} centralStores={false}>
|
|
{children}
|
|
</Providers>
|
|
),
|
|
}
|
|
)
|
|
|
|
await waitFor(() => expect(count(api, 'user.user.getSelfData')).toBeGreaterThan(0))
|
|
const before = count(api, 'user.user.getSelfData')
|
|
|
|
// Fire-and-forget: awaiting mutateAsync would deadlock under fake timers,
|
|
// because httpBatchLink flushes on a timer that only `waitFor` advances.
|
|
act(() => {
|
|
result.current.mutation.mutate({ name: 'New Name' })
|
|
})
|
|
|
|
await waitFor(() =>
|
|
expect(count(api, 'user.user.getSelfData')).toBeGreaterThan(before)
|
|
)
|
|
})
|
|
})
|