-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathone-click-contact-info.test.js
More file actions
831 lines (713 loc) · 32.9 KB
/
one-click-contact-info.test.js
File metadata and controls
831 lines (713 loc) · 32.9 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
/*
* 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 {screen, waitFor, fireEvent, act} from '@testing-library/react'
import ContactInfo from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-contact-info'
import {renderWithProviders} from '@salesforce/retail-react-app/app/utils/test-utils'
import {rest} from 'msw'
import {AuthHelpers, useCustomerType} from '@salesforce/commerce-sdk-react'
jest.setTimeout(60000)
const validEmail = 'test@salesforce.com'
const mockAuthHelperFunctions = {
[AuthHelpers.LoginRegisteredUserB2C]: {mutateAsync: jest.fn()},
[AuthHelpers.Logout]: {mutateAsync: jest.fn()},
[AuthHelpers.AuthorizePasswordless]: {mutateAsync: jest.fn()},
[AuthHelpers.LoginPasswordlessUser]: {mutateAsync: jest.fn()}
}
const mockUpdateCustomerForBasket = {mutateAsync: jest.fn()}
const mockTransferBasket = {mutate: jest.fn(), mutateAsync: jest.fn()}
const mockUpdateBillingAddressForBasket = {mutateAsync: jest.fn()}
const mockUpdateCustomer = {mutateAsync: jest.fn()}
jest.mock('@salesforce/commerce-sdk-react', () => {
const originalModule = jest.requireActual('@salesforce/commerce-sdk-react')
return {
...originalModule,
useCustomerType: jest.fn(() => ({isRegistered: false})),
useAuthHelper: jest
.fn()
.mockImplementation((helperType) => mockAuthHelperFunctions[helperType]),
useShopperBasketsMutation: jest.fn().mockImplementation((mutationType) => {
if (mutationType === 'updateCustomerForBasket') return mockUpdateCustomerForBasket
if (mutationType === 'transferBasket') return mockTransferBasket
if (mutationType === 'updateBillingAddressForBasket')
return mockUpdateBillingAddressForBasket
return {mutate: jest.fn()}
}),
useShopperCustomersMutation: jest.fn().mockImplementation((mutationType) => {
if (mutationType === 'updateCustomer') return mockUpdateCustomer
return {mutateAsync: jest.fn()}
})
}
})
const mockUseCurrentBasket = jest.fn(() => ({
data: {
basketId: 'test-basket-id',
customerInfo: {
email: null
},
shipments: [{shipmentId: 'shipment-1', shipmentType: 'delivery'}],
productItems: [{productId: 'product-1', shipmentId: 'shipment-1'}]
},
derivedData: {
hasBasket: true,
totalItems: 1
},
refetch: jest.fn()
}))
jest.mock('@salesforce/retail-react-app/app/hooks/use-current-basket', () => ({
useCurrentBasket: (...args) => mockUseCurrentBasket(...args)
}))
const mockUseCurrentCustomer = jest.fn(() => ({
data: {
email: null,
isRegistered: false
}
}))
jest.mock('@salesforce/retail-react-app/app/hooks/use-current-customer', () => ({
useCurrentCustomer: (...args) => mockUseCurrentCustomer(...args)
}))
const mockSetContactPhone = jest.fn()
const mockGoToNextStep = jest.fn()
jest.mock('@salesforce/retail-react-app/app/pages/checkout-one-click/util/checkout-context', () => {
return {
useCheckout: jest.fn().mockReturnValue({
customer: null,
basket: {basketId: 'test-basket-id'},
isGuestCheckout: true,
setIsGuestCheckout: jest.fn(),
step: 0,
login: null,
STEPS: {CONTACT_INFO: 0},
goToStep: null,
goToNextStep: mockGoToNextStep,
setContactPhone: mockSetContactPhone
})
}
})
const mockAuth = {refreshAccessToken: jest.fn()}
jest.mock('@salesforce/commerce-sdk-react/hooks/useAuthContext', () => jest.fn(() => mockAuth))
jest.mock('@salesforce/retail-react-app/app/hooks/use-multi-site', () => ({
__esModule: true,
default: () => ({
site: {id: 'RefArch'},
locale: {id: 'en-US'},
buildUrl: jest.fn((path) => path)
})
}))
// Mock OtpAuth to expose a verify trigger
jest.mock('@salesforce/retail-react-app/app/components/otp-auth', () => {
// eslint-disable-next-line react/prop-types
return function MockOtpAuth({isOpen, handleOtpVerification, onCheckoutAsGuest}) {
return isOpen ? (
<div>
<div>Confirm it's you</div>
<p>To log in to your account, enter the code sent to your email.</p>
<div>
<button type="button" onClick={onCheckoutAsGuest}>
Checkout as a guest
</button>
<button type="button">Resend Code</button>
</div>
<button data-testid="otp-verify" onClick={() => handleOtpVerification('12345678')}>
Verify
</button>
</div>
) : null
}
})
beforeEach(() => {
jest.clearAllMocks()
// Default: allow OTP authorization so modal can open unless a test overrides it
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockResolvedValue({})
// Reset basket mock to default (delivery shipment)
mockUseCurrentBasket.mockReturnValue({
data: {
basketId: 'test-basket-id',
customerInfo: {email: null},
shipments: [{shipmentId: 'shipment-1', shipmentType: 'delivery'}],
productItems: [{productId: 'product-1', shipmentId: 'shipment-1'}],
billingAddress: null
},
derivedData: {hasBasket: true, totalItems: 1},
refetch: jest.fn()
})
// Reset billing address mutation mock
mockUpdateBillingAddressForBasket.mutateAsync.mockResolvedValue({})
// Reset customer mock to default
mockUseCurrentCustomer.mockReturnValue({
data: {
email: null,
isRegistered: false
}
})
// Reset update customer mock
mockUpdateCustomer.mutateAsync.mockResolvedValue({})
// Reset useCustomerType mock to ensure phone input is not disabled
useCustomerType.mockReturnValue({isRegistered: false})
})
afterEach(() => {})
describe('ContactInfo Component', () => {
beforeEach(() => {
global.server.use(
rest.put('*/baskets/:basketId/customer', (req, res, ctx) => {
return res(
ctx.json({
basketId: 'test-basket-id',
customerInfo: {email: validEmail}
})
)
})
)
})
test('renders basic component structure', () => {
renderWithProviders(<ContactInfo />)
expect(screen.getByLabelText('Email')).toBeInTheDocument()
expect(screen.getByText('Contact Info')).toBeInTheDocument()
expect(screen.getByLabelText('Phone')).toBeInTheDocument()
expect(screen.getByLabelText('Phone')).not.toHaveAttribute('disabled')
})
test('renders email input field', () => {
renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
expect(emailInput).toBeInTheDocument()
expect(emailInput).toHaveAttribute('type', 'email')
})
test('updates checkout contact phone when user types phone (guest)', async () => {
const {user} = renderWithProviders(<ContactInfo />)
const phoneInput = screen.getByLabelText('Phone')
// Type the phone number and wait for it to be formatted
await user.type(phoneInput, '7275551234')
// Wait for the phone input to have a value (formatted phone number)
await waitFor(() => {
const currentValue = phoneInput.value || ''
expect(currentValue.length).toBeGreaterThan(0)
})
// Verify the phone number was formatted (should contain parentheses and/or dashes)
expect(phoneInput.value).toMatch(/[0-9]/)
})
test('shows phone disabled and prefilled for registered shopper', async () => {
jest.resetModules()
jest.doMock('@salesforce/commerce-sdk-react', () => {
const originalModule = jest.requireActual('@salesforce/commerce-sdk-react')
return {
...originalModule,
useCustomerType: jest.fn(() => ({isRegistered: true})),
useAuthHelper: jest
.fn()
.mockImplementation(
(helperType) =>
mockAuthHelperFunctions[helperType] || {mutateAsync: jest.fn()}
)
}
})
jest.doMock('@salesforce/retail-react-app/app/hooks/use-current-customer', () => ({
useCurrentCustomer: () => ({
data: {
email: 'reg@salesforce.com',
isRegistered: true,
phoneHome: '(111) 222-3333'
}
})
}))
const {renderWithProviders: localRenderWithProviders} = await import(
'@salesforce/retail-react-app/app/utils/test-utils'
)
const module = await import(
'@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-contact-info'
)
const Component = module.default
localRenderWithProviders(<Component />)
const phoneInput = screen.getByLabelText('Phone')
expect(phoneInput).toBeInTheDocument()
expect(phoneInput).toHaveAttribute('disabled')
})
test('displays phone number in summary card for registered user', async () => {
jest.resetModules()
jest.doMock('@salesforce/commerce-sdk-react', () => {
const originalModule = jest.requireActual('@salesforce/commerce-sdk-react')
return {
...originalModule,
useCustomerType: jest.fn(() => ({isRegistered: true})),
useAuthHelper: jest
.fn()
.mockImplementation(
(helperType) =>
mockAuthHelperFunctions[helperType] || {mutateAsync: jest.fn()}
)
}
})
jest.doMock('@salesforce/retail-react-app/app/hooks/use-current-customer', () => ({
useCurrentCustomer: () => ({
data: {
email: 'reg@salesforce.com',
isRegistered: true,
phoneHome: '(111) 222-3333'
}
})
}))
jest.doMock(
'@salesforce/retail-react-app/app/pages/checkout-one-click/util/checkout-context',
() => {
return {
useCheckout: jest.fn().mockReturnValue({
customer: null,
basket: {basketId: 'test-basket-id'},
isGuestCheckout: false,
setIsGuestCheckout: jest.fn(),
step: 1, // Not on CONTACT_INFO step, so summary shows
login: null,
STEPS: {CONTACT_INFO: 0},
goToStep: jest.fn(),
goToNextStep: jest.fn(),
setContactPhone: jest.fn()
})
}
}
)
const {renderWithProviders: localRenderWithProviders} = await import(
'@salesforce/retail-react-app/app/utils/test-utils'
)
const module = await import(
'@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-contact-info'
)
const Component = module.default
localRenderWithProviders(<Component />)
// Verify email and phone are displayed in summary
expect(screen.getByText('reg@salesforce.com')).toBeInTheDocument()
expect(screen.getByText('(111) 222-3333')).toBeInTheDocument()
})
test('shows social login when enabled', () => {
renderWithProviders(<ContactInfo isSocialEnabled={true} idps={['google', 'apple']} />)
expect(screen.getByText('Or Login With')).toBeInTheDocument()
expect(screen.getByRole('button', {name: /Google/i})).toBeInTheDocument()
expect(screen.getByRole('button', {name: /Apple/i})).toBeInTheDocument()
})
test('does not show social login when disabled', () => {
renderWithProviders(<ContactInfo isSocialEnabled={false} />)
expect(screen.queryByText('Or Login With')).not.toBeInTheDocument()
expect(screen.queryByRole('button', {name: /Google/i})).not.toBeInTheDocument()
})
test('validates email is required on blur', async () => {
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
// Enter email and then clear it to trigger validation
await user.type(emailInput, 'test@example.com')
await user.clear(emailInput)
// Explicitly blur to trigger our custom blur handler
fireEvent.blur(emailInput)
await waitFor(() => {
const matches = screen.queryAllByText((_, node) =>
node?.textContent?.includes('Please enter your email address.')
)
expect(matches.length).toBeGreaterThan(0)
})
})
test('validates email is required on form submission', async () => {
// Test the validation logic directly by simulating form submission
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
// Try to submit with empty email by pressing Enter
await user.type(emailInput, '{enter}')
// The validation should prevent submission and show error
await waitFor(() => {
expect(screen.getAllByText('Please enter your email address.').length).toBeGreaterThan(
0
)
})
})
test('validates email format on form submission', async () => {
// Test the validation logic directly
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
// Enter invalid email and trigger blur validation
await user.type(emailInput, 'invalid-email')
fireEvent.blur(emailInput)
await waitFor(() => {
expect(
screen.getAllByText('Please enter a valid email address.').length
).toBeGreaterThan(0)
})
// Should not show required email error
expect(screen.queryByText('Please enter your email address.')).not.toBeInTheDocument()
})
test('allows guest checkout with valid email', async () => {
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
// Ensure value committed to RHF before blur
fireEvent.change(emailInput, {target: {value: validEmail}})
fireEvent.blur(emailInput)
await waitFor(() => {
const continueBtn = screen.getByRole('button', {
name: /continue to shipping address/i
})
expect(continueBtn).toBeEnabled()
})
})
test('opens OTP modal for registered email on blur', async () => {
// Mock successful passwordless login authorization
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockResolvedValue({
success: true
})
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
fireEvent.blur(emailInput)
await waitFor(() => {
expect(screen.getByText("Confirm it's you")).toBeInTheDocument()
})
// Verify authorize passwordless was called with correct parameters
expect(
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync
).toHaveBeenCalledWith({
userid: validEmail,
mode: 'email',
locale: 'en-US'
})
})
test('renders continue button for guest checkout', async () => {
// Mock the passwordless login to fail (email not found)
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockRejectedValue(
new Error('Email not found')
)
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
fireEvent.blur(emailInput)
await waitFor(() => {
const continueBtn = screen.getByRole('button', {
name: /continue to shipping address/i
})
expect(continueBtn).toBeEnabled()
})
})
test('renders "Continue to Payment" button for BOPIS-only orders', async () => {
// Mock BOPIS-only basket
mockUseCurrentBasket.mockReturnValue({
data: {
basketId: 'test-basket-id',
customerInfo: {email: null},
shipments: [{shipmentId: 'pickup-1', c_fromStoreId: 'store-123'}],
productItems: [{productId: 'product-1', shipmentId: 'pickup-1'}]
},
derivedData: {hasBasket: true, totalItems: 1},
refetch: jest.fn()
})
// Mock the passwordless login to fail (guest checkout)
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockRejectedValue(
new Error('Email not found')
)
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
fireEvent.blur(emailInput)
await waitFor(() => {
const continueBtn = screen.getByRole('button', {
name: /continue to payment/i
})
expect(continueBtn).toBeEnabled()
})
// Verify "Continue to Shipping Address" is NOT shown
expect(
screen.queryByRole('button', {name: /continue to shipping address/i})
).not.toBeInTheDocument()
})
test('requires phone for guest shoppers on submit', async () => {
// Ensure guest path (no OTP modal)
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockRejectedValue(
new Error('Email not found')
)
const {user} = renderWithProviders(<ContactInfo />)
// Enter valid email, leave phone empty
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
fireEvent.change(emailInput, {target: {value: validEmail}})
fireEvent.blur(emailInput)
// Click continue
const continueBtn = await screen.findByRole('button', {
name: /continue to shipping address/i
})
await user.click(continueBtn)
// Should not proceed or update basket without phone
expect(mockUpdateCustomerForBasket.mutateAsync).not.toHaveBeenCalled()
expect(mockGoToNextStep).not.toHaveBeenCalled()
})
test('handles OTP authorization failure gracefully', async () => {
// Mock the passwordless login to fail
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockRejectedValue(
new Error('Authorization failed')
)
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
fireEvent.blur(emailInput)
// Should show enabled continue button for guest checkout when OTP fails
await waitFor(() => {
const continueBtn = screen.getByRole('button', {
name: /continue to shipping address/i
})
expect(continueBtn).toBeEnabled()
})
})
test('renders contact info title', () => {
renderWithProviders(<ContactInfo />)
expect(screen.getByText('Contact Info')).toBeInTheDocument()
})
test('does not render password-related fields', () => {
renderWithProviders(<ContactInfo />)
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument()
expect(screen.queryByText('Forgot password?')).not.toBeInTheDocument()
expect(screen.queryByText('Log In')).not.toBeInTheDocument()
})
test('does not render passwordless login options', () => {
renderWithProviders(<ContactInfo />)
expect(screen.queryByText('Secure Link')).not.toBeInTheDocument()
expect(screen.queryByText('Password')).not.toBeInTheDocument()
expect(screen.queryByText('Already have an account? Log in')).not.toBeInTheDocument()
expect(screen.queryByText('Back to Sign In Options')).not.toBeInTheDocument()
})
test('renders OTP modal content correctly', async () => {
// Mock successful OTP authorization
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockResolvedValue({
success: true
})
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
fireEvent.blur(emailInput)
// Wait for OTP modal to appear
await waitFor(() => {
expect(screen.getByText("Confirm it's you")).toBeInTheDocument()
})
// Verify modal content
expect(
screen.getByText('To log in to your account, enter the code sent to your email.')
).toBeInTheDocument()
expect(screen.getByText(/Checkout as a guest/i)).toBeInTheDocument()
expect(screen.getByText(/Resend Code/i)).toBeInTheDocument()
})
test('opens OTP modal when form is submitted by clicking submit button', async () => {
// Mock successful OTP authorization
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockResolvedValue({
success: true
})
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
// Commit before submit and ensure RHF picks up value
fireEvent.change(emailInput, {target: {value: validEmail}})
await act(async () => {
fireEvent.input(emailInput, {target: {value: validEmail}})
})
fireEvent.blur(emailInput)
await user.click(emailInput) // focus clears any emailError
// Find and click the submit button
const submitButton = screen.getByRole('button', {
name: /continue to shipping address/i
})
await user.click(submitButton)
// Wait for OTP modal to appear after form submission
await screen.findByTestId('otp-verify')
// Verify modal content is present
expect(
screen.getByText('To log in to your account, enter the code sent to your email.')
).toBeInTheDocument()
expect(screen.getByText(/Checkout as a guest/i)).toBeInTheDocument()
expect(screen.getByText(/Resend Code/i)).toBeInTheDocument()
})
test('shows error message when updateCustomerForBasket fails', async () => {
// Mock OTP authorization to succeed so modal opens
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockResolvedValue({})
// Mock update to fail when choosing guest
mockUpdateCustomerForBasket.mutateAsync.mockRejectedValue(new Error('API Error'))
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
fireEvent.change(emailInput, {target: {value: validEmail}})
await act(async () => {
fireEvent.input(emailInput, {target: {value: validEmail}})
})
// Open OTP modal via submit
const submitButton = screen.getByRole('button', {name: /continue to shipping address/i})
await user.click(submitButton)
await screen.findByTestId('otp-verify')
// Click "Checkout as a guest" which triggers updateCustomerForBasket and should set error
await user.click(screen.getByText(/Checkout as a guest/i))
await waitFor(() => {
expect(mockUpdateCustomerForBasket.mutateAsync).toHaveBeenCalled()
})
// Error alert should be rendered with API error message
await waitFor(() => {
const alerts = screen.queryAllByRole('alert')
const hasError = alerts.some((n) => n.textContent?.includes('API Error'))
expect(hasError).toBe(true)
})
})
test('does not proceed to next step when OTP modal is already open on form submission', async () => {
// Mock successful OTP authorization
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockResolvedValue({
success: true
})
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
// Commit email, then open OTP modal via blur
fireEvent.change(emailInput, {target: {value: validEmail}})
await act(async () => {
fireEvent.input(emailInput, {target: {value: validEmail}})
})
fireEvent.blur(emailInput)
// Wait for OTP modal to appear
await screen.findByTestId('otp-verify')
// Now try to submit the form while modal is already open
// We'll use fireEvent.submit on the form instead of clicking the button
const form = emailInput.closest('form')
fireEvent.submit(form)
// Verify that the OTP modal is still open and we haven't proceeded to next step
expect(screen.getByText("Confirm it's you")).toBeInTheDocument()
expect(
screen.getByText('To log in to your account, enter the code sent to your email.')
).toBeInTheDocument()
// The modal should still be visible, indicating we didn't proceed to the next step
expect(screen.getByText(/Checkout as a guest/i)).toBeInTheDocument()
expect(screen.getByText(/Resend Code/i)).toBeInTheDocument()
})
test('OTP verification transfers and updates basket email using transferred id', async () => {
// Arrange mocks
mockAuthHelperFunctions[AuthHelpers.LoginPasswordlessUser].mutateAsync.mockResolvedValue({})
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockResolvedValue({})
const mergedId = 'merged-123'
mockTransferBasket.mutateAsync.mockResolvedValue({basketId: mergedId})
// Make refetch return merged id to simulate hydration
const refetchSpy = jest.fn().mockResolvedValue({data: {basketId: mergedId}})
mockUseCurrentBasket.mockReturnValue({
data: {basketId: 'guest-1', productItems: [{}], shipments: [{}]},
derivedData: {hasBasket: true, totalItems: 1},
refetch: refetchSpy
})
// Ensure update succeeds
mockUpdateCustomerForBasket.mutateAsync.mockResolvedValue({})
// Act: render and open modal then verify
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, 'test@salesforce.com')
// Commit email, then open OTP modal via submit
fireEvent.change(emailInput, {target: {value: 'test@salesforce.com'}})
await act(async () => {
fireEvent.input(emailInput, {target: {value: 'test@salesforce.com'}})
})
fireEvent.blur(emailInput)
const submitForMerge = screen.getByRole('button', {
name: /continue to shipping address/i
})
await user.click(submitForMerge)
// Click our mocked verify button to invoke handleOtpVerification
await screen.findByTestId('otp-verify')
await user.click(screen.getByTestId('otp-verify'))
// Simulate auth state flip to registered to trigger merge effect on next render
useCustomerType.mockReturnValue({isRegistered: true})
await waitFor(() => {
expect(mockTransferBasket.mutateAsync).toHaveBeenCalled()
// Validate transferBasket called with merge=true parameter
const transferArgs = mockTransferBasket.mutateAsync.mock.calls[0]?.[0]
expect(transferArgs?.parameters).toMatchObject({merge: true})
})
// Updating basket email may occur asynchronously or be skipped if unchanged; don't hard-require it here
})
test('defaults phone number from basket billing address when customer phone is not available', () => {
// Mock basket with billing address phone
mockUseCurrentBasket.mockReturnValue({
data: {
basketId: 'test-basket-id',
customerInfo: {email: null},
shipments: [{shipmentId: 'shipment-1', shipmentType: 'delivery'}],
productItems: [{productId: 'product-1', shipmentId: 'shipment-1'}],
billingAddress: {phone: '(555) 123-4567'}
},
derivedData: {hasBasket: true, totalItems: 1},
refetch: jest.fn()
})
renderWithProviders(<ContactInfo />)
const phoneInput = screen.getByLabelText('Phone')
expect(phoneInput.value).toBe('(555) 123-4567')
})
test('saves phone number to billing address when guest checks out via "Checkout as Guest" button', async () => {
// Mock successful OTP authorization to open modal
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockResolvedValue({})
mockUpdateCustomerForBasket.mutateAsync.mockResolvedValue({})
mockUpdateBillingAddressForBasket.mutateAsync.mockResolvedValue({})
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
const phoneInput = screen.getByLabelText('Phone')
// Enter phone first - use fireEvent to ensure value is set
fireEvent.change(phoneInput, {target: {value: '(727) 555-1234'}})
// Enter email and wait for OTP modal to open
await user.type(emailInput, validEmail)
fireEvent.change(emailInput, {target: {value: validEmail}})
fireEvent.blur(emailInput)
// Wait for OTP modal to open
await screen.findByTestId('otp-verify')
// Click "Checkout as a guest" button
await user.click(screen.getByText(/Checkout as a guest/i))
await waitFor(() => {
expect(mockUpdateBillingAddressForBasket.mutateAsync).toHaveBeenCalled()
const callArgs = mockUpdateBillingAddressForBasket.mutateAsync.mock.calls[0]?.[0]
expect(callArgs?.parameters).toMatchObject({basketId: 'test-basket-id'})
expect(callArgs?.body?.phone).toMatch(/727/)
})
})
test('uses phone from billing address when persisting to customer profile after OTP verification', async () => {
// Mock basket with billing address phone
const billingPhone = '(555) 123-4567'
mockUseCurrentBasket.mockReturnValue({
data: {
basketId: 'test-basket-id',
customerInfo: {email: null},
shipments: [{shipmentId: 'shipment-1', shipmentType: 'delivery'}],
productItems: [{productId: 'product-1', shipmentId: 'shipment-1'}],
billingAddress: {phone: billingPhone}
},
derivedData: {hasBasket: true, totalItems: 1},
refetch: jest.fn().mockResolvedValue({
data: {
basketId: 'test-basket-id',
billingAddress: {phone: billingPhone}
}
})
})
// Mock OTP verification flow
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockResolvedValue({})
mockAuthHelperFunctions[AuthHelpers.LoginPasswordlessUser].mutateAsync.mockResolvedValue({})
mockTransferBasket.mutateAsync.mockResolvedValue({basketId: 'test-basket-id'})
mockUpdateCustomerForBasket.mutateAsync.mockResolvedValue({})
// Mock customer with customerId after login - update mock to return customer with ID
mockUseCurrentCustomer.mockReturnValue({
data: {
email: validEmail,
isRegistered: true,
customerId: 'customer-123'
}
})
const {user} = renderWithProviders(<ContactInfo />)
const emailInput = screen.getByLabelText('Email')
await user.type(emailInput, validEmail)
fireEvent.change(emailInput, {target: {value: validEmail}})
fireEvent.blur(emailInput)
// Wait for OTP modal and verify
await screen.findByTestId('otp-verify')
await user.click(screen.getByTestId('otp-verify'))
// Simulate auth state change to registered
useCustomerType.mockReturnValue({isRegistered: true})
await waitFor(() => {
// Verify updateCustomer was called with phone from billing address
expect(mockUpdateCustomer.mutateAsync).toHaveBeenCalledWith({
parameters: {customerId: 'customer-123'},
body: {phoneHome: billingPhone}
})
})
})
})