-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathindex.test.js
More file actions
895 lines (759 loc) · 32.8 KB
/
index.test.js
File metadata and controls
895 lines (759 loc) · 32.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import React from 'react'
import PropTypes from 'prop-types'
import {fireEvent, screen, waitFor} from '@testing-library/react'
import mockProductDetail from '@salesforce/retail-react-app/app/mocks/variant-750518699578M'
import mockProductSet from '@salesforce/retail-react-app/app/mocks/product-set-winter-lookM'
import {mockProductBundle} from '@salesforce/retail-react-app/app/mocks/product-bundle'
import {
mockStandardProductOrderable,
mockStandardProductNotOrderable
} from '@salesforce/retail-react-app/app/mocks/standard-product'
import ProductView from '@salesforce/retail-react-app/app/components/product-view'
import {renderWithProviders} from '@salesforce/retail-react-app/app/utils/test-utils'
import userEvent from '@testing-library/user-event'
import {useCurrentCustomer} from '@salesforce/retail-react-app/app/hooks/use-current-customer'
import frMessages from '@salesforce/retail-react-app/app/static/translations/compiled/fr-FR.json'
import {useSelectedStore} from '@salesforce/retail-react-app/app/hooks/use-selected-store'
import {rest} from 'msw'
// Ensure useMultiSite returns site.id = 'site-1' for all tests
jest.mock('@salesforce/retail-react-app/app/hooks/use-multi-site', () => ({
__esModule: true,
default: () => ({
site: {id: 'site-1'},
buildUrl: (url) => url // identity function for tests
})
}))
// Mock useSelectedStore hook
jest.mock('@salesforce/retail-react-app/app/hooks/use-selected-store', () => ({
useSelectedStore: jest.fn()
}))
const MockComponent = (props) => {
const {data: customer} = useCurrentCustomer()
return (
<div>
<div>customer: {customer?.authType}</div>
<ProductView {...props} />
</div>
)
}
MockComponent.propTypes = {
product: PropTypes.object,
addToCart: PropTypes.func,
addToWishlist: PropTypes.func,
updateWishlist: PropTypes.func,
isBasketLoading: PropTypes.bool
}
const mockStoreData = {
id: 'store-1',
name: 'Test Store Location',
inventoryId: 'inventory_m_store_store1'
}
// Set up and clean up
beforeEach(() => {
// Since we're testing some navigation logic, we are using a simple Router
// around our component. We need to initialize the default route/path here.
window.history.pushState({}, 'Account', '/en/account')
useSelectedStore.mockImplementation(() => ({
selectedStore: mockStoreData,
isLoading: false,
error: null,
hasSelectedStore: true
}))
// Reset MSW handlers to avoid conflicts
global.server.resetHandlers()
// Add MSW handlers to avoid 403 errors
global.server.use(
rest.get('*/customers/:customerId/product-lists', (req, res, ctx) => {
return res(
ctx.delay(0),
ctx.status(200),
ctx.json({
data: [],
total: 0
})
)
}),
rest.post('*/customers/:customerId/product-lists', (req, res, ctx) => {
return res(
ctx.delay(0),
ctx.status(200),
ctx.json({
id: 'test-list-id',
type: 'wish_list'
})
)
}),
rest.get('*/configuration/shopper-configurations/*', (req, res, ctx) => {
return res(
ctx.delay(0),
ctx.status(200),
ctx.json({
configurations: []
})
)
}),
rest.get('*/product/shopper-products/*', (req, res, ctx) => {
return res(
ctx.delay(0),
ctx.status(200),
ctx.json({
data: []
})
)
}),
rest.get('*/api/payment-metadata', (req, res, ctx) => {
return res(
ctx.delay(0),
ctx.status(200),
ctx.json({
apiKey: 'test-key',
publishableKey: 'pk_test'
})
)
})
)
})
afterEach(() => {
jest.clearAllMocks()
sessionStorage.clear()
})
// Update MockComponent default props for all tests
MockComponent.defaultProps = {
pickupInStore: false,
setPickupInStore: jest.fn()
}
test('ProductView Component renders properly', async () => {
const addToCart = jest.fn()
renderWithProviders(<MockComponent product={mockProductDetail} addToCart={addToCart} />)
expect(screen.getAllByText(/Black Single Pleat Athletic Fit Wool Suit/i)).toHaveLength(2)
expect(screen.getAllByText(/299\.99/)).toHaveLength(4)
expect(screen.getAllByText(/Add to cart/i)).toHaveLength(2)
expect(screen.getAllByRole('radiogroup')).toHaveLength(4)
expect(screen.getAllByText(/add to cart/i)).toHaveLength(2)
})
describe('Event Handlers', () => {
test('calls addToCart when add to cart button is clicked', async () => {
const addToCart = jest.fn()
await renderWithProviders(
<MockComponent product={mockProductDetail} addToCart={addToCart} />
)
const addToCartButton = screen.getAllByText(/add to cart/i)[0]
fireEvent.click(addToCartButton)
await waitFor(() => {
expect(addToCart).toHaveBeenCalledTimes(1)
})
})
test('calls addToWishlist when add to wishlist button is clicked', async () => {
const addToWishlist = jest.fn()
await renderWithProviders(
<MockComponent product={mockProductDetail} addToWishlist={addToWishlist} />
)
await waitFor(() => {
expect(screen.getByText(/customer: registered/)).toBeInTheDocument()
})
await waitFor(() => {
const addToWishListButton = screen.getAllByText(/Add to wishlist/i)[0]
fireEvent.click(addToWishListButton)
expect(addToWishlist).toHaveBeenCalledTimes(1)
})
})
test('calls updateWishlist when update button is clicked', async () => {
const updateWishlist = jest.fn()
await renderWithProviders(
<MockComponent product={mockProductDetail} updateWishlist={updateWishlist} />
)
await waitFor(() => {
expect(screen.getByText(/customer: registered/)).toBeInTheDocument()
})
await waitFor(() => {
const updateWishlistButton = screen.getAllByText(/Update/i)[0]
fireEvent.click(updateWishlistButton)
expect(updateWishlist).toHaveBeenCalledTimes(1)
})
})
test('calls onVariantSelected after variant selection', async () => {
const user = userEvent.setup()
const onVariantSelected = jest.fn()
const child = mockProductSet.setProducts[0]
renderWithProviders(
<MockComponent
product={child}
onVariantSelected={onVariantSelected}
addToCart={() => {}}
addToWishlist={() => {}}
/>
)
const size = screen.getByRole('radio', {name: /xl/i})
await user.click(size)
await waitFor(() => {
expect(onVariantSelected).toHaveBeenCalledTimes(1)
})
})
test('calls validateOrderability when adding a set to cart', async () => {
const user = userEvent.setup()
const parent = mockProductSet
const validateOrderability = jest.fn()
renderWithProviders(
<MockComponent
product={parent}
validateOrderability={validateOrderability}
addToCart={() => {}}
addToWishlist={() => {}}
/>
)
const button = screen.getByRole('button', {name: /add set to cart/i})
await user.click(button)
await waitFor(() => {
expect(validateOrderability).toHaveBeenCalledTimes(1)
})
})
test('calls onVariantSelected for standard products in bundles', async () => {
const onVariantSelected = jest.fn()
const setChildProductOrderability = jest.fn()
const standardProduct = {
id: 'standard-product-1',
name: 'Standard Product',
type: {item: true},
variationAttributes: [],
inventory: {
orderable: true,
stockLevel: 10
}
}
renderWithProviders(
<MockComponent
product={standardProduct}
onVariantSelected={onVariantSelected}
setChildProductOrderability={setChildProductOrderability}
isProductPartOfBundle={true}
childOfBundleQuantity={2}
addToCart={() => {}}
addToWishlist={() => {}}
/>
)
await waitFor(() => {
expect(onVariantSelected).toHaveBeenCalledWith(standardProduct, null, 2)
})
})
test('calls onVariantSelected for standard products in sets', async () => {
const onVariantSelected = jest.fn()
const setChildProductOrderability = jest.fn()
const standardProduct = {
id: 'standard-product-1',
name: 'Standard Product',
type: {item: true},
variationAttributes: [],
inventory: {
orderable: true,
stockLevel: 10
}
}
renderWithProviders(
<MockComponent
product={standardProduct}
onVariantSelected={onVariantSelected}
setChildProductOrderability={setChildProductOrderability}
isProductPartOfSet={true}
addToCart={() => {}}
addToWishlist={() => {}}
/>
)
await waitFor(() => {
expect(onVariantSelected).toHaveBeenCalledWith(standardProduct, null, 1)
})
})
})
describe('Quantity Management', () => {
test('can update quantity through input field', async () => {
const user = userEvent.setup()
const addToCart = jest.fn()
await renderWithProviders(
<MockComponent product={mockProductDetail} addToCart={addToCart} />
)
let quantityBox
await waitFor(() => {
quantityBox = screen.getByRole('spinbutton')
})
await waitFor(() => {
expect(quantityBox).toHaveValue('1')
})
// update item quantity
await user.type(quantityBox, '{backspace}3')
await waitFor(() => {
expect(quantityBox).toHaveValue('3')
})
})
test('handles invalid quantity inputs by resetting to minimum', async () => {
const user = userEvent.setup()
// Any invalid input should be reset to minOrderQuantity
await renderWithProviders(<MockComponent product={mockProductDetail} />)
const quantityInput = screen.getByRole('spinbutton', {name: /quantity/i})
const minQuantity = mockProductDetail.minOrderQuantity.toString()
// Quantity is empty
await user.clear(quantityInput)
await user.tab()
await waitFor(() => {
expect(quantityInput).toHaveValue(minQuantity)
})
// Quantity is zero
await user.clear(quantityInput)
await user.type(quantityInput, '0')
await user.tab()
await waitFor(() => {
expect(quantityInput).toHaveValue(minQuantity)
})
})
test('quantity picker renders with increment/decrement buttons', async () => {
renderWithProviders(<ProductView product={mockProductDetail} />)
const quantityInput = await screen.findByRole('spinbutton')
const incrementButton = screen.getByTestId('quantity-increment')
const decrementButton = screen.getByTestId('quantity-decrement')
// Wait for the component to initialize with the correct value
await waitFor(() => {
expect(quantityInput).toHaveValue('1')
})
// Test that increment/decrement buttons exist and are accessible
expect(incrementButton).toBeInTheDocument()
expect(decrementButton).toBeInTheDocument()
expect(incrementButton).toBeEnabled()
expect(decrementButton).toBeEnabled()
// Test that buttons have proper accessibility attributes
expect(incrementButton).toHaveAttribute('aria-label')
expect(decrementButton).toHaveAttribute('aria-label')
})
})
describe('Loading States', () => {
test('disables add to cart button when basket is loading', async () => {
renderWithProviders(
<MockComponent
product={mockProductDetail}
addToCart={() => {}}
isBasketLoading={true}
/>
)
expect(screen.getByRole('button', {name: /add to cart/i})).toBeDisabled()
})
test('enables add to cart button when basket is not loading', async () => {
renderWithProviders(
<MockComponent
product={mockProductDetail}
addToCart={() => {}}
isBasketLoading={false}
/>
)
expect(screen.getByRole('button', {name: /add to cart/i})).toBeEnabled()
})
})
describe('Product Sets', () => {
test('renders parent item correctly', () => {
const parent = mockProductSet
renderWithProviders(
<MockComponent product={parent} addToCart={() => {}} addToWishlist={() => {}} />
)
// NOTE: there can be duplicates of the same element, due to mobile and desktop views
// (they're hidden with display:none style)
const fromAtLabel = screen.getAllByText(/from/i)[0]
const addSetToCartButton = screen.getAllByRole('button', {name: /add set to cart/i})[0]
const addSetToWishlistButton = screen.getAllByRole('button', {
name: /add set to wishlist/i
})[0]
const variationAttributes = screen
.queryAllByRole('radiogroup')
.filter(
(rg) =>
!rg.textContent.includes('Ship to Address') &&
!rg.textContent.includes('Pickup in Store')
)
const quantityPicker = screen.queryByRole('spinbutton', {name: /quantity/i})
// What should exist:
expect(fromAtLabel).toBeInTheDocument()
expect(addSetToCartButton).toBeInTheDocument()
expect(addSetToWishlistButton).toBeInTheDocument()
// What should _not_ exist:
expect(variationAttributes).toHaveLength(0)
expect(quantityPicker).toBeNull()
})
test('renders child item correctly', () => {
const child = mockProductSet.setProducts[0]
renderWithProviders(
<MockComponent product={child} addToCart={() => {}} addToWishlist={() => {}} />
)
// NOTE: there can be duplicates of the same element, due to mobile and desktop views
// (they're hidden with display:none style)
const addToCartButton = screen.getAllByRole('button', {name: /add to cart/i})[0]
const addToWishlistButton = screen.getAllByRole('button', {name: /add to wishlist/i})[0]
const variationAttributes = screen
.queryAllByRole('radiogroup')
.filter(
(rg) =>
!rg.textContent.includes('Ship to Address') &&
!rg.textContent.includes('Pickup in Store')
)
const quantityPicker = screen.getByRole('spinbutton', {name: /quantity/i})
const fromLabels = screen.queryAllByText(/from/i)
// What should exist:
expect(addToCartButton).toBeInTheDocument()
expect(addToWishlistButton).toBeInTheDocument()
expect(variationAttributes).toHaveLength(2)
expect(quantityPicker).toBeInTheDocument()
// since setProducts are master products, as pricing now display From X (cross) Y where X Y are sale and lis price respectively
// of the variant that has lowest price (including promotional price)
expect(fromLabels).toHaveLength(4)
})
})
describe('Product Bundles', () => {
test('renders parent item correctly', () => {
const parent = mockProductBundle
renderWithProviders(
<MockComponent product={parent} addToCart={() => {}} addToWishlist={() => {}} />
)
// NOTE: there can be duplicates of the same element, due to mobile and desktop views
// (they're hidden with display:none style)
const addBundleToCartButton = screen.getAllByRole('button', {
name: /add bundle to cart/i
})[0]
const addBundleToWishlistButton = screen.getAllByRole('button', {
name: /add bundle to wishlist/i
})[0]
const quantityPicker = screen.getByRole('spinbutton', {name: /quantity/i})
const variationAttributes = screen
.queryAllByRole('radiogroup')
.filter(
(rg) =>
!rg.textContent.includes('Ship to Address') &&
!rg.textContent.includes('Pickup in Store')
)
// What should exist:
expect(addBundleToCartButton).toBeInTheDocument()
expect(addBundleToWishlistButton).toBeInTheDocument()
expect(quantityPicker).toBeInTheDocument()
// What should _not_ exist:
expect(variationAttributes).toHaveLength(0)
})
test('renders child item correctly', () => {
const child = mockProductBundle.bundledProducts[0].product
renderWithProviders(
<MockComponent
product={child}
addToCart={() => {}}
addToWishlist={() => {}}
isProductPartOfBundle={true}
setChildProductOrderability={() => {}}
/>
)
const addToCartButton = screen.queryByRole('button', {name: /add to cart/i})
const addToWishlistButton = screen.queryByRole('button', {name: /add to wishlist/i})
const variationAttributes = screen
.queryAllByRole('radiogroup')
.filter(
(rg) =>
!rg.textContent.includes('Ship to Address') &&
!rg.textContent.includes('Pickup in Store')
)
const quantityPicker = screen.queryByRole('spinbutton', {name: /quantity:/i})
// What should exist:
expect(variationAttributes).toHaveLength(2)
// What should _not_ exist:
expect(addToCartButton).toBeNull()
expect(addToWishlistButton).toBeNull()
expect(quantityPicker).toBeNull()
})
test('Pickup in store radio is enabled when selected store is set', async () => {
// Ensure the product has inventory data for the store and is in stock
const mockProduct = {
...mockProductDetail,
inventories: [{id: mockStoreData.inventoryId, orderable: true, stockLevel: 10}]
}
renderWithProviders(<MockComponent product={mockProduct} showDeliveryOptions={true} />)
// Assert: Radio is enabled
const pickupRadio = await screen.findByRole('radio', {name: /pick up in store/i})
expect(pickupRadio).toBeEnabled()
})
test('Pickup in store radio is disabled when inventoryId is NOT present in localStorage', async () => {
renderWithProviders(
<MockComponent product={mockProductDetail} showDeliveryOptions={true} />
)
// Assert: Radio is disabled
const pickupRadio = await screen.findByRole('radio', {name: /pick up in store/i})
expect(pickupRadio).toBeDisabled()
})
test('Pickup in store radio is disabled when inventoryId is present but product is out of stock', async () => {
const user = userEvent.setup()
// Product inventory is not orderable
const mockProduct = {
...mockProductDetail,
inventories: [{id: mockStoreData.inventoryId, orderable: false}]
}
renderWithProviders(<MockComponent product={mockProduct} showDeliveryOptions={true} />)
const pickupRadio = await screen.findByRole('radio', {name: /pick up in store/i})
// Chakra UI does not set a semantic disabled attribute, so we test for unclickability
expect(pickupRadio).not.toBeChecked()
await user.click(pickupRadio)
expect(pickupRadio).not.toBeChecked()
})
test('shows "Pickup in Select Store" label when pickup is disabled due to no store/inventoryId', async () => {
useSelectedStore.mockReturnValue({
selectedStore: null,
isLoading: false,
error: null,
hasSelectedStore: false
})
renderWithProviders(
<MockComponent product={mockProductDetail} showDeliveryOptions={true} />
)
const label = await screen.findByTestId('pickup-select-store-msg')
expect(label).toBeInTheDocument()
expect(label).toHaveTextContent(/Pick up in/i)
const button = label.querySelector('button')
expect(button).toBeInTheDocument()
expect(button).toHaveTextContent(/Select Store/i)
})
describe('ProductView stock status messages', () => {
const storeName = 'Test Store'
test('shows "In Stock at {storeName}" when store has inventory', async () => {
const mockProduct = {
...mockProductDetail,
inventories: [{id: mockStoreData.inventoryId, orderable: true, stockLevel: 10}],
name: 'Test Product'
}
renderWithProviders(<MockComponent product={mockProduct} showDeliveryOptions={true} />)
const msg = await screen.findByText(/In Stock at/i)
expect(msg).toBeInTheDocument()
expect(msg).toHaveTextContent(storeName)
// Store name should be a button
const button = msg.querySelector('button')
expect(button).toBeInTheDocument()
expect(button).toHaveTextContent(storeName)
})
test('shows "Out of Stock at {storeName}" when store is out of inventory', async () => {
const mockProduct = {
...mockProductDetail,
inventories: [{id: mockStoreData.inventoryId, orderable: false}],
name: 'Test Product'
}
renderWithProviders(<MockComponent product={mockProduct} showDeliveryOptions={true} />)
const msg = await screen.findByText(/Out of Stock at/i)
expect(msg).toBeInTheDocument()
expect(msg).toHaveTextContent(storeName)
// Store name should be a button
const button = msg.querySelector('button')
expect(button).toBeInTheDocument()
expect(button).toHaveTextContent(storeName)
})
})
describe('ProductView showDeliveryOptions property', () => {
test('shows delivery options when showDeliveryOptions is true (default)', async () => {
renderWithProviders(
<MockComponent product={mockProductDetail} showDeliveryOptions={true} />
)
// Delivery options should be visible
expect(screen.getByText(/Delivery:/i)).toBeInTheDocument()
expect(screen.getByRole('radio', {name: /ship to address/i})).toBeInTheDocument()
expect(screen.getByRole('radio', {name: /pick up in store/i})).toBeInTheDocument()
})
test('hides delivery options when showDeliveryOptions is false', async () => {
renderWithProviders(
<MockComponent product={mockProductDetail} showDeliveryOptions={false} />
)
// Delivery options should not be visible
expect(screen.queryByText(/Delivery:/i)).not.toBeInTheDocument()
expect(screen.queryByRole('radio', {name: /ship to address/i})).not.toBeInTheDocument()
expect(screen.queryByRole('radio', {name: /pick up in store/i})).not.toBeInTheDocument()
expect(screen.queryByTestId('store-stock-status-msg')).not.toBeInTheDocument()
expect(screen.queryByTestId('pickup-select-store-msg')).not.toBeInTheDocument()
})
test('shows delivery options when showDeliveryOptions is not provided (defaults to true)', async () => {
renderWithProviders(<MockComponent product={mockProductDetail} />)
// Delivery options should be visible by default
expect(screen.getByText(/Delivery:/i)).toBeInTheDocument()
expect(screen.getByRole('radio', {name: /ship to address/i})).toBeInTheDocument()
expect(screen.getByRole('radio', {name: /pick up in store/i})).toBeInTheDocument()
})
})
})
// Additional tests from develop branch
test('Pick up in store radio is enabled when selected store is set', async () => {
// Ensure the product has inventory data for the store and is in stock
const mockProduct = {
...mockProductDetail,
inventories: [{id: mockStoreData.inventoryId, orderable: true, stockLevel: 10}]
}
renderWithProviders(<MockComponent product={mockProduct} showDeliveryOptions={true} />)
// Assert: Radio is enabled
const pickupRadio = await screen.findByRole('radio', {name: /pick up in store/i})
expect(pickupRadio).toBeEnabled()
})
test('Pick up in store radio is disabled when inventoryId is NOT present in selected store', async () => {
renderWithProviders(<MockComponent product={mockProductDetail} showDeliveryOptions={true} />)
// Assert: Radio is disabled
const pickupRadio = await screen.findByRole('radio', {name: /pick up in store/i})
expect(pickupRadio).toBeDisabled()
})
test('Pick up in store radio is disabled when inventoryId is present but product is out of stock', async () => {
const user = userEvent.setup()
// Product inventory is not orderable
const mockProduct = {
...mockProductDetail,
inventories: [{id: mockStoreData.inventoryId, orderable: false}]
}
renderWithProviders(<MockComponent product={mockProduct} showDeliveryOptions={true} />)
const pickupRadio = await screen.findByRole('radio', {name: /pick up in store/i})
// Chakra UI does not set a semantic disabled attribute, so we test for unclickability
expect(pickupRadio).not.toBeChecked()
await user.click(pickupRadio)
expect(pickupRadio).not.toBeChecked()
})
test('shows "Pick up in Select Store" label when pickup is disabled due to no store/inventoryId', async () => {
useSelectedStore.mockReturnValue({
selectedStore: null,
isLoading: false,
error: null,
hasSelectedStore: false
})
renderWithProviders(<MockComponent product={mockProductDetail} showDeliveryOptions={true} />)
const label = await screen.findByTestId('pickup-select-store-msg')
expect(label).toBeInTheDocument()
expect(label).toHaveTextContent(/Pick up in/i)
const button = label.querySelector('button')
expect(button).toBeInTheDocument()
expect(button).toHaveTextContent(/Select Store/i)
})
test('shows "In stock at {storeName}" when store has inventory', async () => {
const mockProduct = {
...mockProductDetail,
inventories: [{id: mockStoreData.inventoryId, orderable: true, stockLevel: 10}]
}
renderWithProviders(<MockComponent product={mockProduct} showDeliveryOptions={true} />)
const msg = await screen.findByText(/In stock at/i)
expect(msg).toBeInTheDocument()
expect(msg).toHaveTextContent('Test Store')
// Store name should be a button
const button = msg.querySelector('button')
expect(button).toBeInTheDocument()
expect(button).toHaveTextContent('Test Store')
})
test('renders "Add to Cart" and "Add to Wishlist" buttons in French', async () => {
const addToCart = jest.fn()
const addToWishlist = jest.fn()
renderWithProviders(
<MockComponent
product={mockProductDetail}
addToCart={addToCart}
addToWishlist={addToWishlist}
/>,
{
wrapperProps: {locale: {id: 'fr-FR'}, messages: frMessages}
}
)
const titles = await screen.findAllByText(/Black Single Pleat Athletic Fit Wool Suit/i)
expect(titles.length).toBeGreaterThan(0)
expect(screen.getByRole('button', {name: /ajouter au panier/i})).toBeInTheDocument()
expect(
screen.getByRole('button', {name: /ajouter à la liste de souhaits/i})
).toBeInTheDocument()
})
describe('validateOrderability', () => {
test('returns true when variant is undefined but product is orderable', () => {
const validateOrderability = (variant, product, quantity, stockLevel) =>
(variant?.orderable || product?.inventory?.orderable) &&
quantity > 0 &&
quantity <= stockLevel
const variant = undefined
const product = mockStandardProductOrderable
const quantity = 1
const stockLevel = 999999
const result = validateOrderability(variant, product, quantity, stockLevel)
expect(result).toBe(true)
})
test('returns false when variant is undefined and product is not orderable', () => {
const validateOrderability = (variant, product, quantity, stockLevel) =>
(variant?.orderable || product?.inventory?.orderable) &&
quantity > 0 &&
quantity <= stockLevel
const variant = undefined
const product = mockStandardProductNotOrderable
const quantity = 1
const stockLevel = 0
const result = validateOrderability(variant, product, quantity, stockLevel)
expect(result).toBe(false)
})
test('returns true when variant is orderable regardless of product orderability', () => {
const validateOrderability = (variant, product, quantity, stockLevel) =>
(variant?.orderable || product?.inventory?.orderable) &&
quantity > 0 &&
quantity <= stockLevel
const variant = {orderable: true}
const product = mockStandardProductNotOrderable // product is not orderable
const quantity = 1
const stockLevel = 999999
const result = validateOrderability(variant, product, quantity, stockLevel)
expect(result).toBe(true)
})
test('returns false when both variant and product are not orderable', () => {
const validateOrderability = (variant, product, quantity, stockLevel) =>
(variant?.orderable || product?.inventory?.orderable) &&
quantity > 0 &&
quantity <= stockLevel
const variant = {orderable: false}
const product = mockStandardProductNotOrderable
const quantity = 1
const stockLevel = 0
const result = validateOrderability(variant, product, quantity, stockLevel)
expect(result).toBe(false)
})
test('returns false when quantity is invalid even if product/variant are orderable', () => {
const validateOrderability = (variant, product, quantity, stockLevel) =>
(variant?.orderable || product?.inventory?.orderable) &&
quantity > 0 &&
quantity <= stockLevel
const variant = undefined
const product = mockStandardProductOrderable
const quantity = 0 // invalid quantity
const stockLevel = 999999
const result = validateOrderability(variant, product, quantity, stockLevel)
expect(result).toBe(false)
})
test('returns false when quantity exceeds stock level', () => {
const validateOrderability = (variant, product, quantity, stockLevel) =>
(variant?.orderable || product?.inventory?.orderable) &&
quantity > 0 &&
quantity <= stockLevel
const variant = undefined
const product = mockStandardProductOrderable
const quantity = 1000000 // exceeds stock level
const stockLevel = 999999
const result = validateOrderability(variant, product, quantity, stockLevel)
expect(result).toBe(false)
})
})
// Test maxOrderQuantity prop functionality
describe('maxOrderQuantity Prop', () => {
test('quantity picker respects maxOrderQuantity prop', async () => {
const addToCart = jest.fn()
renderWithProviders(
<MockComponent product={mockProductDetail} addToCart={addToCart} maxOrderQuantity={3} />
)
const quantityInput = screen.getByRole('spinbutton')
const incrementButton = screen.getByTestId('quantity-increment')
const decrementButton = screen.getByTestId('quantity-decrement')
// Test that quantity picker renders with max constraint
await waitFor(() => {
expect(quantityInput).toHaveValue('1')
})
// Test that buttons are present and accessible
expect(incrementButton).toBeInTheDocument()
expect(decrementButton).toBeInTheDocument()
expect(incrementButton).toBeEnabled()
expect(decrementButton).toBeEnabled()
// Test that the input has proper accessibility attributes
expect(quantityInput).toHaveAttribute('aria-label')
expect(incrementButton).toHaveAttribute('aria-label')
expect(decrementButton).toHaveAttribute('aria-label')
})
})