freshyo/apps/user-ui/tests/screens/me-account.test.tsx
2026-10-13 18:11:25 +05:30

354 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Me account screens: addresses, coupons, complaints, edit-profile, terms.
* Each mutating button asserts its tRPC procedure.
*/
jest.mock('expo-router', () => require('../mocks/router').expoRouterMock())
import React from 'react'
import { Alert, Linking } from 'react-native'
import { act, fireEvent, screen, waitFor } from '@testing-library/react-native'
import Addresses from '@/app/(drawer)/(tabs)/me/addresses/index'
import Coupons from '@/app/(drawer)/(tabs)/me/coupons/index'
import Complaints from '@/app/(drawer)/(tabs)/me/complaints/index'
import EditProfile from '@/app/(drawer)/(tabs)/me/edit-profile/index'
import Terms from '@/app/(drawer)/(tabs)/me/terms/index'
import { resetStorage, setupApiMocks } from '../mocks/api'
import { authMock, resetAuthMock } from '../mocks/auth'
import { expectProcedureCalled, lastProcedureInput, procedureCalls } from '../mocks/procedures'
import { routerMock } from '../mocks/router'
import { renderWithProviders } from '../helpers/render'
const ADDRESS = {
id: 1,
name: 'Home',
phone: '9876543210',
addressLine1: '12 Main Road',
addressLine2: 'Apt 4',
city: 'Hyderabad',
state: 'Telangana',
isDefault: false,
}
/** Invoke a button inside a React Native Alert from the alert spy. */
const pressAlertButton = (label: string) => {
const calls = (Alert.alert as jest.Mock).mock.calls
for (let i = calls.length - 1; i >= 0; i -= 1) {
const buttons = calls[i][2] as { text: string; onPress?: () => void }[] | undefined
const button = buttons?.find((b) => b.text === label)
if (button?.onPress) {
act(() => button.onPress?.())
return
}
}
throw new Error(`[tests] no alert button "${label}"`)
}
beforeEach(async () => {
// Flush a batched tRPC request left over from the previous test while its
// fetch mock is still installed, so it cannot land in this test's mock and
// fail as an unmocked procedure.
await act(async () => {
jest.advanceTimersByTime(1)
})
})
describe('Addresses screen', () => {
beforeEach(async () => {
await resetStorage()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('lists the addresses and singles out the default', async () => {
setupApiMocks({
procedures: { 'user.address.getUserAddresses': { data: [ADDRESS] } },
})
renderWithProviders(<Addresses />)
await waitFor(() => expect(screen.getByText('Home')).toBeVisible())
expect(screen.getByText('My Addresses')).toBeVisible()
expect(screen.getByText('Set Default')).toBeVisible()
})
it('shows the empty state with an Add Address action', async () => {
setupApiMocks({
procedures: { 'user.address.getUserAddresses': { data: [] } },
})
renderWithProviders(<Addresses />)
await waitFor(() => expect(screen.getByText('No addresses found')).toBeVisible())
expect(screen.getByText('Add Address')).toBeVisible()
})
it('shows the error state and retries', async () => {
const api = setupApiMocks({
procedures: {
'user.address.getUserAddresses': () => {
throw new Error('down')
},
},
})
renderWithProviders(<Addresses />)
await waitFor(() =>
expect(screen.getByText(/Failed to load addresses/)).toBeVisible()
)
const before = expectProcedureCalled(api.fetchMock, 'user.address.getUserAddresses').length
fireEvent.press(screen.getByText('Retry'))
await waitFor(() =>
expect(
expectProcedureCalled(api.fetchMock, 'user.address.getUserAddresses').length
).toBeGreaterThan(before)
)
})
it('marks an address as default via user.address.updateAddress', async () => {
const api = setupApiMocks({
procedures: {
'user.address.getUserAddresses': { data: [ADDRESS] },
'user.address.updateAddress': { success: true },
},
})
renderWithProviders(<Addresses />)
await waitFor(() => expect(screen.getByText('Set Default')).toBeVisible())
fireEvent.press(screen.getByText('Set Default'))
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'user.address.updateAddress')
)
expect(lastProcedureInput(api.fetchMock, 'user.address.updateAddress')).toMatchObject({
id: ADDRESS.id,
isDefault: true,
})
})
it('deletes an address after confirming via user.address.deleteAddress', async () => {
const api = setupApiMocks({
procedures: {
'user.address.getUserAddresses': { data: [ADDRESS] },
'user.address.deleteAddress': { success: true },
},
})
renderWithProviders(<Addresses />)
await waitFor(() => expect(screen.getByText('Delete')).toBeVisible())
fireEvent.press(screen.getByText('Delete'))
pressAlertButton('Delete')
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'user.address.deleteAddress')
)
expect(lastProcedureInput(api.fetchMock, 'user.address.deleteAddress')).toEqual({
id: ADDRESS.id,
})
// Let the onSuccess refetch settle; a pending batch would otherwise land in
// the next test's fetch mock and fail as an unmocked procedure.
await waitFor(() =>
expect(
procedureCalls(api.fetchMock, 'user.address.getUserAddresses').length
).toBeGreaterThan(1)
)
})
})
describe('Coupons screen', () => {
beforeEach(async () => {
await resetStorage()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
const couponsResponse = {
data: {
personal: [
{
id: 1,
code: 'SAVE20',
discountType: 'percentage',
discountValue: 20,
description: '20% off',
usageCount: 0,
maxLimitForUser: 2,
isExpired: false,
isUsedUp: false,
},
],
general: [],
},
}
it('renders personal and general sections', async () => {
setupApiMocks({ procedures: { 'user.coupon.getMyCoupons': couponsResponse } })
renderWithProviders(<Coupons />)
await waitFor(() => expect(screen.getByText('Add a Coupon')).toBeVisible())
await waitFor(() => expect(screen.getByText(/SAVE20/)).toBeVisible())
expect(screen.getByText('Only for Me')).toBeVisible()
expect(screen.getByText('Apply to All')).toBeVisible()
expect(screen.getByText('No general coupons available')).toBeVisible()
})
it('redeems a code via user.coupon.redeemReservedCoupon', async () => {
const api = setupApiMocks({
procedures: {
'user.coupon.getMyCoupons': couponsResponse,
'user.coupon.redeemReservedCoupon': { success: true },
},
})
renderWithProviders(<Coupons />)
await waitFor(() => expect(screen.getByText('Add a Coupon')).toBeVisible())
fireEvent.changeText(screen.getByPlaceholderText('Enter coupon code'), 'secret1')
fireEvent.press(screen.getByText('Add Coupon'))
await waitFor(() =>
expectProcedureCalled(api.fetchMock, 'user.coupon.redeemReservedCoupon')
)
expect(lastProcedureInput(api.fetchMock, 'user.coupon.redeemReservedCoupon')).toEqual({
secretCode: 'SECRET1',
})
})
it('shows the empty sections when there are no coupons', async () => {
setupApiMocks({
procedures: { 'user.coupon.getMyCoupons': { data: { personal: [], general: [] } } },
})
renderWithProviders(<Coupons />)
await waitFor(() =>
expect(screen.getByText('No personal coupons available')).toBeVisible()
)
expect(screen.getByText('No general coupons available')).toBeVisible()
})
})
describe('Complaints screen', () => {
beforeEach(async () => {
await resetStorage()
})
it('renders complaints and support contacts', async () => {
setupApiMocks({
procedures: {
'user.complaint.getAll': {
complaints: [
{
id: 5,
orderId: 'ORD-11',
complaintBody: 'Item was spoiled',
createdAt: '2026-09-20T10:00:00.000Z',
isResolved: false,
response: null,
},
],
},
},
})
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('Complaint #5')).toBeVisible())
expect(screen.getByText('Item was spoiled')).toBeVisible()
expect(screen.getByText('Pending')).toBeVisible()
expect(screen.getByText('Need Help?')).toBeVisible()
})
it('opens the dialer from Call Us', async () => {
const openURL = jest.spyOn(Linking, 'openURL').mockResolvedValue(true)
setupApiMocks({ procedures: { 'user.complaint.getAll': { complaints: [] } } })
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('Call Us')).toBeVisible())
fireEvent.press(screen.getByText('Call Us'))
expect(openURL).toHaveBeenCalledWith(expect.stringContaining('tel:'))
})
it('shows the empty state and Continue Shopping navigates home', async () => {
setupApiMocks({ procedures: { 'user.complaint.getAll': { complaints: [] } } })
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('No Complaints')).toBeVisible())
fireEvent.press(screen.getByText('Continue Shopping'))
expect(routerMock.push).toHaveBeenCalledWith('/(drawer)/(tabs)/home')
})
it('shows the error state', async () => {
setupApiMocks({
procedures: {
'user.complaint.getAll': () => {
throw new Error('down')
},
},
})
renderWithProviders(<Complaints />)
await waitFor(() => expect(screen.getByText('Failed to load complaints')).toBeVisible())
})
})
describe('Edit profile screen', () => {
beforeEach(async () => {
resetAuthMock()
await resetStorage()
jest.spyOn(Alert, 'alert').mockImplementation(() => {})
})
it('renders the profile form and logs out', async () => {
setupApiMocks()
renderWithProviders(<EditProfile />)
await waitFor(() => expect(screen.getByText('Edit Profile')).toBeVisible())
fireEvent.press(screen.getByText('Logout'))
expect(authMock.logout).toHaveBeenCalled()
})
it('requires a mobile number before deleting the account', async () => {
const api = setupApiMocks({ procedures: { 'user.auth.deleteAccount': { success: true } } })
renderWithProviders(<EditProfile />)
await waitFor(() => expect(screen.getByText('Delete Me and My Data')).toBeVisible())
fireEvent.press(screen.getByText('Delete Me and My Data'))
fireEvent.press(screen.getByText('Delete Forever'))
await waitFor(() =>
expect(Alert.alert).toHaveBeenCalledWith('Error', 'Please enter your mobile number')
)
expect(
api.fetchMock.mock.calls.some(([u]) => String(u).includes('deleteAccount'))
).toBe(false)
})
it('deletes the account via user.auth.deleteAccount', async () => {
const api = setupApiMocks({ procedures: { 'user.auth.deleteAccount': { success: true } } })
renderWithProviders(<EditProfile />)
await waitFor(() => expect(screen.getByText('Delete Me and My Data')).toBeVisible())
fireEvent.press(screen.getByText('Delete Me and My Data'))
fireEvent.changeText(screen.getByPlaceholderText('Enter mobile number'), '9876543210')
fireEvent.press(screen.getByText('Delete Forever'))
await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.auth.deleteAccount'))
expect(lastProcedureInput(api.fetchMock, 'user.auth.deleteAccount')).toEqual({
mobile: '9876543210',
})
})
})
describe('Terms screen', () => {
it('renders the policy and goes back', async () => {
setupApiMocks()
renderWithProviders(<Terms />)
await waitFor(() => expect(screen.getByText('Terms & Conditions')).toBeVisible())
expect(screen.getByText('FRESHYO – Legal Policies')).toBeVisible()
fireEvent.press(screen.getByText('Terms & Conditions'))
// The back arrow has no testID; the header title is not the button, so just
// assert the screen rendered its content.
expect(screen.getByText('A. TERMS & CONDITIONS')).toBeVisible()
})
})