2
0

OrderButtonBar.test.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import { render, fireEvent, waitFor } from '@testing-library/react'
  2. import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
  3. import { mockShowModal, mockShowToast, mockGetNetworkType, mockGetEnv } from '~/__mocks__/taroMock'
  4. import OrderButtonBar from '@/components/order/OrderButtonBar'
  5. // Mock API client
  6. jest.mock('@/api', () => ({
  7. orderClient: {
  8. cancelOrder: {
  9. $post: jest.fn()
  10. }
  11. }
  12. }))
  13. // Mock CancelReasonDialog 组件
  14. jest.mock('@/components/common/CancelReasonDialog', () => {
  15. const React = require('react')
  16. const MockCancelReasonDialog = ({ open, onOpenChange, onConfirm, loading }: any) => {
  17. const [reason, setReason] = React.useState('')
  18. const [error, setError] = React.useState('')
  19. if (!open) return null
  20. const handleConfirm = () => {
  21. const trimmedReason = reason.trim()
  22. if (!trimmedReason) {
  23. setError('请输入取消原因')
  24. return
  25. }
  26. if (trimmedReason.length < 5) {
  27. setError('取消原因至少需要5个字符')
  28. return
  29. }
  30. if (trimmedReason.length > 200) {
  31. setError('取消原因不能超过200个字符')
  32. return
  33. }
  34. setError('')
  35. onConfirm(trimmedReason)
  36. }
  37. // 预定义原因选项
  38. const CANCEL_REASONS = [
  39. '我不想买了',
  40. '信息填写错误,重新下单',
  41. '商家缺货',
  42. '价格不合适',
  43. '其他原因'
  44. ]
  45. return React.createElement('div', { 'data-testid': 'cancel-reason-dialog' }, [
  46. React.createElement('div', { key: 'title' }, '取消订单'),
  47. React.createElement('div', { key: 'description' }, '请选择或填写取消原因,这将帮助我们改进服务'),
  48. // 预定义原因选项
  49. React.createElement('div', { key: 'reasons' },
  50. CANCEL_REASONS.map((reasonText, index) =>
  51. React.createElement('div', {
  52. key: index,
  53. onClick: () => {
  54. setReason(reasonText)
  55. if (error) setError('')
  56. }
  57. }, reasonText)
  58. )
  59. ),
  60. React.createElement('input', {
  61. key: 'reason-input',
  62. placeholder: '请输入其他取消原因...',
  63. value: reason,
  64. onChange: (e: any) => {
  65. setReason(e.target.value)
  66. if (error) setError('')
  67. }
  68. }),
  69. error && React.createElement('div', { key: 'error', 'data-testid': 'error-message' }, error),
  70. React.createElement('button', {
  71. key: 'confirm',
  72. onClick: handleConfirm,
  73. disabled: loading
  74. }, loading ? '提交中...' : '确认取消'),
  75. React.createElement('button', {
  76. key: 'cancel',
  77. onClick: () => onOpenChange(false)
  78. }, '取消')
  79. ])
  80. }
  81. MockCancelReasonDialog.displayName = 'MockCancelReasonDialog'
  82. return MockCancelReasonDialog
  83. })
  84. const mockOrder = {
  85. id: 1,
  86. orderNo: 'ORDER001',
  87. payState: 0, // 未支付
  88. state: 0, // 未发货
  89. amount: 100,
  90. payAmount: 100,
  91. freightAmount: 0,
  92. discountAmount: 0,
  93. goodsDetail: JSON.stringify([
  94. { id: 1, name: '商品1', price: 50, num: 2, image: '', spec: '默认规格' }
  95. ]),
  96. recevierName: '张三',
  97. receiverMobile: '13800138000',
  98. address: '北京市朝阳区',
  99. createdAt: '2025-01-01T00:00:00Z'
  100. }
  101. const createTestQueryClient = () => new QueryClient({
  102. defaultOptions: {
  103. queries: { retry: false },
  104. mutations: { retry: false }
  105. }
  106. })
  107. const TestWrapper = ({ children }: { children: React.ReactNode }) => (
  108. <QueryClientProvider client={createTestQueryClient()}>
  109. {children}
  110. </QueryClientProvider>
  111. )
  112. describe('OrderButtonBar', () => {
  113. beforeEach(() => {
  114. jest.clearAllMocks()
  115. // 模拟网络检查成功回调
  116. mockGetNetworkType.mockImplementation((options) => {
  117. if (options?.success) {
  118. options.success({ networkType: 'wifi' })
  119. }
  120. return Promise.resolve()
  121. })
  122. // 模拟环境检查
  123. mockGetEnv.mockReturnValue('WEB')
  124. })
  125. it('should render cancel button for unpaid order', () => {
  126. const { getByText } = render(
  127. <TestWrapper>
  128. <OrderButtonBar order={mockOrder} onViewDetail={jest.fn()} />
  129. </TestWrapper>
  130. )
  131. expect(getByText('取消订单')).toBeTruthy()
  132. expect(getByText('去支付')).toBeTruthy()
  133. expect(getByText('查看详情')).toBeTruthy()
  134. })
  135. it('should show cancel reason dialog when cancel button is clicked', async () => {
  136. const { getByText, getByTestId } = render(
  137. <TestWrapper>
  138. <OrderButtonBar order={mockOrder} onViewDetail={jest.fn()} />
  139. </TestWrapper>
  140. )
  141. fireEvent.click(getByText('取消订单'))
  142. await waitFor(() => {
  143. expect(getByTestId('cancel-reason-dialog')).toBeTruthy()
  144. // 检查对话框内容
  145. expect(getByText('请选择或填写取消原因,这将帮助我们改进服务')).toBeTruthy()
  146. })
  147. })
  148. it('should call API when cancel order is confirmed', async () => {
  149. const mockApiCall = require('@/api').orderClient.cancelOrder.$post as jest.Mock
  150. mockShowModal.mockResolvedValueOnce({ confirm: true }) // 确认取消
  151. mockApiCall.mockResolvedValue({ status: 200, json: () => Promise.resolve({ success: true, message: '取消成功' }) })
  152. const { getByText, getByPlaceholderText, getByTestId } = render(
  153. <TestWrapper>
  154. <OrderButtonBar order={mockOrder} onViewDetail={jest.fn()} />
  155. </TestWrapper>
  156. )
  157. // 打开取消对话框
  158. fireEvent.click(getByText('取消订单'))
  159. await waitFor(() => {
  160. expect(getByTestId('cancel-reason-dialog')).toBeTruthy()
  161. })
  162. // 输入取消原因
  163. const reasonInput = getByPlaceholderText('请输入其他取消原因...')
  164. fireEvent.change(reasonInput, { target: { value: '测试取消原因' } })
  165. // 点击确认取消按钮
  166. fireEvent.click(getByText('确认取消'))
  167. await waitFor(() => {
  168. expect(mockShowModal).toHaveBeenCalledWith({
  169. title: '确认取消',
  170. content: '确定要取消订单吗?\n取消原因:测试取消原因',
  171. success: expect.any(Function)
  172. })
  173. })
  174. // 模拟确认对话框确认
  175. const modalCall = mockShowModal.mock.calls[0][0]
  176. if (modalCall.success) {
  177. modalCall.success({ confirm: true })
  178. }
  179. await waitFor(() => {
  180. expect(mockApiCall).toHaveBeenCalledWith({
  181. json: {
  182. orderId: 1,
  183. reason: '测试取消原因'
  184. }
  185. })
  186. })
  187. })
  188. it('should show error when cancel reason is empty', async () => {
  189. const { getByText, getByTestId } = render(
  190. <TestWrapper>
  191. <OrderButtonBar order={mockOrder} onViewDetail={jest.fn()} />
  192. </TestWrapper>
  193. )
  194. // 打开取消对话框
  195. fireEvent.click(getByText('取消订单'))
  196. await waitFor(() => {
  197. expect(getByTestId('cancel-reason-dialog')).toBeTruthy()
  198. })
  199. // 直接点击确认取消按钮(不输入原因)
  200. fireEvent.click(getByText('确认取消'))
  201. await waitFor(() => {
  202. expect(getByTestId('error-message')).toBeTruthy()
  203. expect(getByText('请输入取消原因')).toBeTruthy()
  204. })
  205. })
  206. it('should handle network error gracefully', async () => {
  207. const mockApiCall = require('@/api').orderClient.cancelOrder.$post as jest.Mock
  208. mockShowModal.mockResolvedValueOnce({ confirm: true })
  209. mockApiCall.mockRejectedValue(new Error('网络连接失败'))
  210. const { getByText, getByPlaceholderText, getByTestId } = render(
  211. <TestWrapper>
  212. <OrderButtonBar order={mockOrder} onViewDetail={jest.fn()} />
  213. </TestWrapper>
  214. )
  215. // 打开取消对话框
  216. fireEvent.click(getByText('取消订单'))
  217. await waitFor(() => {
  218. expect(getByTestId('cancel-reason-dialog')).toBeTruthy()
  219. })
  220. // 输入取消原因
  221. const reasonInput = getByPlaceholderText('请输入其他取消原因...')
  222. fireEvent.change(reasonInput, { target: { value: '测试取消原因' } })
  223. // 点击确认取消按钮
  224. fireEvent.click(getByText('确认取消'))
  225. // 模拟确认对话框确认
  226. await waitFor(() => {
  227. expect(mockShowModal).toHaveBeenCalledWith({
  228. title: '确认取消',
  229. content: '确定要取消订单吗?\n取消原因:测试取消原因',
  230. success: expect.any(Function)
  231. })
  232. })
  233. const modalCall = mockShowModal.mock.calls[0][0]
  234. if (modalCall.success) {
  235. modalCall.success({ confirm: true })
  236. }
  237. await waitFor(() => {
  238. expect(mockShowToast).toHaveBeenCalledWith({
  239. title: '网络连接失败,请检查网络后重试',
  240. icon: 'error',
  241. duration: 3000
  242. })
  243. })
  244. })
  245. it('should disable cancel button during mutation', async () => {
  246. // 模拟mutation正在进行中
  247. const mockApiCall = require('@/api').orderClient.cancelOrder.$post as jest.Mock
  248. mockApiCall.mockImplementation(() => new Promise(() => {})) // 永不resolve的promise
  249. const { getByText, getByPlaceholderText, getByTestId } = render(
  250. <TestWrapper>
  251. <OrderButtonBar order={mockOrder} onViewDetail={jest.fn()} />
  252. </TestWrapper>
  253. )
  254. // 打开取消对话框
  255. fireEvent.click(getByText('取消订单'))
  256. await waitFor(() => {
  257. expect(getByTestId('cancel-reason-dialog')).toBeTruthy()
  258. })
  259. // 输入取消原因
  260. const reasonInput = getByPlaceholderText('请输入其他取消原因...')
  261. fireEvent.change(reasonInput, { target: { value: '测试取消原因' } })
  262. // 点击确认取消按钮
  263. fireEvent.click(getByText('确认取消'))
  264. // 模拟确认对话框确认
  265. await waitFor(() => {
  266. expect(mockShowModal).toHaveBeenCalledWith({
  267. title: '确认取消',
  268. content: '确定要取消订单吗?\n取消原因:测试取消原因',
  269. success: expect.any(Function)
  270. })
  271. })
  272. const modalCall = mockShowModal.mock.calls[0][0]
  273. if (modalCall.success) {
  274. modalCall.success({ confirm: true })
  275. }
  276. // 检查按钮状态
  277. await waitFor(() => {
  278. expect(getByText('取消中...')).toBeTruthy()
  279. })
  280. })
  281. it('should not show cancel button for shipped order', () => {
  282. const shippedOrder = {
  283. ...mockOrder,
  284. payState: 2, // 已支付
  285. state: 1 // 已发货
  286. }
  287. const { queryByText } = render(
  288. <TestWrapper>
  289. <OrderButtonBar order={shippedOrder} onViewDetail={jest.fn()} />
  290. </TestWrapper>
  291. )
  292. expect(queryByText('取消订单')).toBeNull()
  293. expect(queryByText('确认收货')).toBeTruthy()
  294. })
  295. it('should use external cancel handler when provided', async () => {
  296. const mockOnCancelOrder = jest.fn()
  297. const { getByText } = render(
  298. <TestWrapper>
  299. <OrderButtonBar
  300. order={mockOrder}
  301. onViewDetail={jest.fn()}
  302. onCancelOrder={mockOnCancelOrder}
  303. />
  304. </TestWrapper>
  305. )
  306. fireEvent.click(getByText('取消订单'))
  307. await waitFor(() => {
  308. expect(mockOnCancelOrder).toHaveBeenCalled()
  309. })
  310. })
  311. })