381 lines
12 KiB
TypeScript
381 lines
12 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
/**
|
|
* Catalogue section 4.5 — Product detail (`app/(drawer)/dashboard/products/detail/[id].tsx`).
|
|
*/
|
|
import React from 'react'
|
|
import { ActivityIndicator, Alert } from 'react-native'
|
|
import { act, fireEvent, waitFor } from '@testing-library/react-native'
|
|
import * as ImagePicker from 'expo-image-picker'
|
|
import { ImageCarousel, ImageUploader } from 'common-ui'
|
|
|
|
import ProductDetail from '@/app/(drawer)/dashboard/products/detail/[id]'
|
|
import { renderAndFlush, flush } from '../helpers/test-utils'
|
|
import { resetAllMocks } from '../helpers/reset'
|
|
import {
|
|
lastMutationInput,
|
|
procedureInvalidations,
|
|
procedureMutationCalls,
|
|
setProcedure,
|
|
setRawFetchHandler,
|
|
} from '../mocks/trpc-client'
|
|
import { __setParams, router } from '../mocks/expo-router-mock'
|
|
import { PRODUCT_REVIEWS, P_CHICKEN, P_NO_IMAGE } from '../fixtures'
|
|
|
|
jest.mock('@react-navigation/native', () => {
|
|
const React = require('react')
|
|
const actual = jest.requireActual('../mocks/react-navigation-mock')
|
|
const callbacks: Array<() => any> = []
|
|
const useFocusEffect = (callback: any) => {
|
|
React.useEffect(() => {
|
|
callbacks.push(callback)
|
|
const cleanup = callback()
|
|
return () => {
|
|
const index = callbacks.indexOf(callback)
|
|
if (index >= 0) callbacks.splice(index, 1)
|
|
if (typeof cleanup === 'function') cleanup()
|
|
}
|
|
}, [callback])
|
|
}
|
|
return {
|
|
...actual,
|
|
useFocusEffect,
|
|
__focusCallbacks: callbacks,
|
|
__runFocus: () => callbacks.forEach((callback) => callback()),
|
|
}
|
|
})
|
|
|
|
// eslint-disable-next-line import/first
|
|
const navMock = require('@react-navigation/native') as {
|
|
__runFocus: () => void
|
|
__focusCallbacks: Array<() => any>
|
|
}
|
|
|
|
const product = (over: Record<string, any> = {}) => ({
|
|
...P_CHICKEN,
|
|
deals: [],
|
|
tags: [],
|
|
...over,
|
|
})
|
|
|
|
async function renderDetail() {
|
|
const view = await renderAndFlush(<ProductDetail />, { auth: false })
|
|
await flush(2)
|
|
return view
|
|
}
|
|
|
|
async function openReply(view: Awaited<ReturnType<typeof renderDetail>>) {
|
|
fireEvent.press(view.getByText('Reply'))
|
|
await flush()
|
|
}
|
|
|
|
async function submitReply(
|
|
view: Awaited<ReturnType<typeof renderDetail>>,
|
|
text?: string
|
|
) {
|
|
if (text !== undefined) {
|
|
fireEvent.changeText(view.getByPlaceholderText('Write your response here...'), text)
|
|
}
|
|
fireEvent.press(view.getByText('Submit Response'))
|
|
await flush(3)
|
|
}
|
|
|
|
/** Wait for the review-response mutation to land, then return its input. */
|
|
async function responsePayload() {
|
|
await waitFor(() =>
|
|
expect(lastMutationInput('admin.product.respondToReview')).toBeDefined()
|
|
)
|
|
return lastMutationInput('admin.product.respondToReview')
|
|
}
|
|
|
|
describe('Product detail (APDET-01..22)', () => {
|
|
let alertSpy: jest.SpyInstance
|
|
|
|
beforeEach(() => {
|
|
resetAllMocks()
|
|
__setParams({ id: '2' })
|
|
alertSpy = jest.spyOn(Alert, 'alert').mockImplementation(() => undefined)
|
|
setRawFetchHandler(async (_url, init) => {
|
|
if (init?.method === 'PUT') {
|
|
return { ok: true, status: 200, text: async () => '' } as any
|
|
}
|
|
return { ok: true, status: 200, blob: async () => ({ size: 1 }) } as any
|
|
})
|
|
;(ImagePicker.launchImageLibraryAsync as jest.Mock).mockResolvedValue({
|
|
canceled: false,
|
|
assets: [{ uri: 'file:///review.jpg', mimeType: 'image/jpeg', fileName: 'review.jpg' }],
|
|
})
|
|
})
|
|
|
|
afterEach(() => alertSpy?.mockRestore())
|
|
|
|
it('APDET-01: shows a spinner and loading copy', async () => {
|
|
setProcedure('admin.product.getProductById', { mode: 'pending' })
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByText('Loading...')).toBeTruthy()
|
|
expect(view.UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-02: shows Product Not Found with a Go Back action', async () => {
|
|
setProcedure('admin.product.getProductById', { mode: 'error', error: new Error('gone') })
|
|
const view = await renderDetail()
|
|
|
|
expect(await view.findByText('Product Not Found')).toBeTruthy()
|
|
fireEvent.press(view.getByText('Go Back'))
|
|
expect(router.back).toHaveBeenCalled()
|
|
})
|
|
|
|
it('APDET-03: renders the hero carousel, name and variant count', async () => {
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByText('Chicken Breast')).toBeTruthy()
|
|
expect(view.getByText('2 Variants')).toBeTruthy()
|
|
expect(view.UNSAFE_getByType(ImageCarousel)).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-04: renders a gray hero when the product has no images', async () => {
|
|
setProcedure('admin.product.getProductById', {
|
|
data: { product: { ...P_NO_IMAGE, deals: [], tags: [] } },
|
|
})
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByTestId('product-hero-placeholder')).toBeTruthy()
|
|
expect(view.UNSAFE_queryByType(ImageCarousel)).toBeNull()
|
|
})
|
|
|
|
it('APDET-05: calculates the average rating to one decimal', async () => {
|
|
const view = await renderDetail()
|
|
|
|
// Ratings 5 and 3 from the default review fixture.
|
|
expect(view.getByText('4.0')).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-06: with no reviews the rating is "-" and the count is 0', async () => {
|
|
setProcedure('admin.product.getProductReviews', { data: { reviews: [], hasMore: false } })
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByText('-')).toBeTruthy()
|
|
expect(view.getByText('0')).toBeTruthy()
|
|
expect(view.getByText('0 Total')).toBeTruthy()
|
|
expect(view.getByText('No reviews yet')).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-07: renders short and long descriptions with a fallback', async () => {
|
|
setProcedure('admin.product.getProductById', {
|
|
data: { product: product({ longDescription: '' }) },
|
|
})
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByText('Tender boneless breast')).toBeTruthy()
|
|
expect(view.getByText('No detailed description available for this product.')).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-08: renders variant features, prices, flash price and stock', async () => {
|
|
setProcedure('admin.product.getProductById', {
|
|
data: {
|
|
product: product({
|
|
skus: [
|
|
{
|
|
...P_CHICKEN.skus[0],
|
|
marketPrice: '220',
|
|
isFlashAvailable: true,
|
|
flashPrice: '199',
|
|
},
|
|
],
|
|
}),
|
|
},
|
|
})
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByText('quantity')).toBeTruthy()
|
|
expect(view.getByText('500g')).toBeTruthy()
|
|
expect(view.getByText('₹215')).toBeTruthy()
|
|
expect(view.getByText('₹220')).toBeTruthy()
|
|
expect(view.getByText('Flash ₹199')).toBeTruthy()
|
|
expect(view.getByText('In Stock')).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-09: renders special deals with quantity, price and validity', async () => {
|
|
setProcedure('admin.product.getProductById', {
|
|
data: {
|
|
product: product({
|
|
deals: [{ quantity: 2, price: 400, validTill: new Date('2030-01-01').toISOString() }],
|
|
}),
|
|
},
|
|
})
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByText('Special Deals')).toBeTruthy()
|
|
expect(view.getByText('Buy 2')).toBeTruthy()
|
|
expect(view.getByText('₹400')).toBeTruthy()
|
|
expect(view.getByText(/Valid until/)).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-10: renders the review list with user, body and images', async () => {
|
|
setProcedure('admin.product.getProductReviews', {
|
|
data: {
|
|
reviews: [
|
|
{
|
|
...PRODUCT_REVIEWS.reviews[0],
|
|
signedImageUrls: ['https://assets.test/review.jpg'],
|
|
},
|
|
],
|
|
hasMore: false,
|
|
},
|
|
})
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByText('A')).toBeTruthy()
|
|
expect(view.getByText('Great')).toBeTruthy()
|
|
expect(view.getByText('1 Total')).toBeTruthy()
|
|
expect(view.getAllByLabelText('https://assets.test/review.jpg')).toHaveLength(1)
|
|
})
|
|
|
|
it('APDET-11: renders an existing admin response block', async () => {
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByText('Admin Response')).toBeTruthy()
|
|
expect(view.getByText('Thanks')).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-12: a review without a response exposes Reply', async () => {
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByText('Reply')).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-13: Reply opens a dialog that quotes the review', async () => {
|
|
const view = await renderDetail()
|
|
|
|
await openReply(view)
|
|
|
|
expect(view.getByText('Reply to Review')).toBeTruthy()
|
|
expect(view.getByText('Replying to A')).toBeTruthy()
|
|
expect(view.getAllByText('Great').length).toBeGreaterThanOrEqual(1)
|
|
})
|
|
|
|
it('APDET-14: submitting a response uploads, mutates, invalidates and closes', async () => {
|
|
const view = await renderDetail()
|
|
|
|
await openReply(view)
|
|
await submitReply(view, 'Thanks for the feedback')
|
|
|
|
expect(await responsePayload()).toEqual({
|
|
reviewId: 1,
|
|
adminResponse: 'Thanks for the feedback',
|
|
adminResponseImages: [],
|
|
uploadUrls: [],
|
|
})
|
|
await waitFor(() =>
|
|
expect(procedureInvalidations('admin.product.getProductReviews')).toHaveLength(1)
|
|
)
|
|
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Success', 'Response submitted'))
|
|
expect(view.queryByText('Reply to Review')).toBeNull()
|
|
})
|
|
|
|
it('APDET-15: an empty response is submitted as-is', async () => {
|
|
const view = await renderDetail()
|
|
|
|
await openReply(view)
|
|
await submitReply(view)
|
|
|
|
expect(await responsePayload()).toEqual(
|
|
expect.objectContaining({ reviewId: 1, adminResponse: '' })
|
|
)
|
|
})
|
|
|
|
it('APDET-16: a pending response shows a spinner', async () => {
|
|
setProcedure('admin.product.respondToReview', { mode: 'pending' })
|
|
const view = await renderDetail()
|
|
|
|
await openReply(view)
|
|
fireEvent.press(view.getByText('Submit Response'))
|
|
await flush(2)
|
|
|
|
expect(view.UNSAFE_getAllByType(ActivityIndicator).length).toBeGreaterThan(0)
|
|
expect(view.queryByText('Submit Response')).toBeNull()
|
|
})
|
|
|
|
it('APDET-17: a failed response alerts and keeps the dialog open', async () => {
|
|
setProcedure('admin.product.respondToReview', {
|
|
mode: 'error',
|
|
error: new Error('respond failed'),
|
|
})
|
|
const view = await renderDetail()
|
|
|
|
await openReply(view)
|
|
await submitReply(view, 'hello')
|
|
|
|
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'respond failed'))
|
|
expect(view.getByText('Reply to Review')).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-18: Edit opens the edit route', async () => {
|
|
const view = await renderDetail()
|
|
|
|
fireEvent.press(view.getByText('Edit'))
|
|
|
|
expect(router.push).toHaveBeenCalledWith('/(drawer)/dashboard/products/edit?id=2')
|
|
})
|
|
|
|
it('APDET-19: the back button calls router.back', async () => {
|
|
const view = await renderDetail()
|
|
|
|
fireEvent.press(view.getByTestId('product-detail-back'))
|
|
|
|
expect(router.back).toHaveBeenCalled()
|
|
})
|
|
|
|
it('APDET-20: a focus refetches through the marked data fetcher', async () => {
|
|
const view = await renderDetail()
|
|
|
|
expect(navMock.__focusCallbacks.length).toBeGreaterThan(0)
|
|
await act(async () => {
|
|
navMock.__runFocus()
|
|
})
|
|
|
|
expect(view.getByText('Chicken Breast')).toBeTruthy()
|
|
})
|
|
|
|
it('APDET-21: a review image upload failure alerts and skips the response', async () => {
|
|
setProcedure('common.generateUploadUrls', { mode: 'error', error: new Error('upload failed') })
|
|
const view = await renderDetail()
|
|
|
|
await openReply(view)
|
|
|
|
const uploader = view.UNSAFE_getByType(ImageUploader)
|
|
await act(async () => {
|
|
uploader.props.onAddImage()
|
|
})
|
|
await flush()
|
|
|
|
await submitReply(view, 'with image')
|
|
|
|
await waitFor(() => expect(alertSpy).toHaveBeenCalledWith('Error', 'upload failed'))
|
|
expect(procedureMutationCalls('admin.product.respondToReview')).toHaveLength(0)
|
|
})
|
|
|
|
it('APDET-22: many variants and reviews render without crashing', async () => {
|
|
const manySkus = Array.from({ length: 25 }, (_, index) => ({
|
|
...P_CHICKEN.skus[0],
|
|
id: 500 + index,
|
|
features: [
|
|
{ id: 500 + index, skuId: 500 + index, featureName: 'quantity', featureValue: `${index + 1}kg` },
|
|
],
|
|
}))
|
|
const manyReviews = Array.from({ length: 30 }, (_, index) => ({
|
|
...PRODUCT_REVIEWS.reviews[0],
|
|
id: 900 + index,
|
|
userName: `User ${index}`,
|
|
reviewBody: `Review ${index}`,
|
|
}))
|
|
setProcedure('admin.product.getProductById', { data: { product: product({ skus: manySkus }) } })
|
|
setProcedure('admin.product.getProductReviews', { data: { reviews: manyReviews, hasMore: false } })
|
|
|
|
const view = await renderDetail()
|
|
|
|
expect(view.getByText('25 Variants')).toBeTruthy()
|
|
expect(view.getByText('30 Total')).toBeTruthy()
|
|
expect(view.getByText('User 0')).toBeTruthy()
|
|
})
|
|
})
|