-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathindex.test.js
More file actions
668 lines (554 loc) · 24.5 KB
/
index.test.js
File metadata and controls
668 lines (554 loc) · 24.5 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
/*
* Copyright (c) 2026, 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} from '@testing-library/react'
import {renderWithProviders} from '@salesforce/retail-react-app/app/utils/test-utils'
import mockConfig from '@salesforce/retail-react-app/config/mocks/default'
import {rest} from 'msw'
// Unmock the component so we can test it
jest.unmock('@salesforce/retail-react-app/app/components/passkey-registration-modal')
import PasskeyRegistrationModal from '@salesforce/retail-react-app/app/components/passkey-registration-modal/index'
// Mock Commerce SDK hooks
const mockMutateAsync = jest.fn()
const mockUseAuthHelper = jest.fn()
jest.mock('@salesforce/commerce-sdk-react', () => ({
...jest.requireActual('@salesforce/commerce-sdk-react'),
useAuthHelper: (param) => mockUseAuthHelper(param),
AuthHelpers: {
AuthorizeWebauthnRegistration: 'AuthorizeWebauthnRegistration',
StartWebauthnUserRegistration: 'StartWebauthnUserRegistration',
FinishWebauthnUserRegistration: 'FinishWebauthnUserRegistration'
}
}))
// Mock useCurrentCustomer
const mockUseCurrentCustomer = jest.fn()
jest.mock('@salesforce/retail-react-app/app/hooks/use-current-customer', () => ({
useCurrentCustomer: () => mockUseCurrentCustomer()
}))
// Mock OtpAuth component - expose handleOtpVerification for testing
let otpVerificationHandler = null
jest.mock('@salesforce/retail-react-app/app/components/otp-auth', () => {
const PropTypes = jest.requireActual('prop-types')
const React = jest.requireActual('react')
const MockOtpAuth = ({isOpen, handleOtpVerification}) => {
React.useEffect(() => {
if (handleOtpVerification) {
otpVerificationHandler = handleOtpVerification
}
}, [handleOtpVerification])
return isOpen ? <div data-testid="otp-auth-modal">OTP Auth Modal</div> : null
}
MockOtpAuth.propTypes = {
isOpen: PropTypes.bool,
handleOtpVerification: PropTypes.func
}
return MockOtpAuth
})
describe('PasskeyRegistrationModal', () => {
const mockOnClose = jest.fn()
const mockCustomer = {
email: 'test@example.com'
}
function PasskeyRegistrationModalWrapper() {
const [isOpen, setIsOpen] = React.useState(true)
return <PasskeyRegistrationModal isOpen={isOpen} onClose={() => setIsOpen(false)} />
}
beforeEach(() => {
jest.clearAllMocks()
otpVerificationHandler = null
mockUseCurrentCustomer.mockReturnValue({
data: mockCustomer
})
mockUseAuthHelper.mockReturnValue({
mutateAsync: mockMutateAsync
})
// Mock WebAuthn API
global.navigator.credentials = {
create: jest.fn()
}
// Mock PublicKeyCredential API
global.PublicKeyCredential = {
parseCreationOptionsFromJSON: jest.fn((options) => ({
challenge: new Uint8Array([1, 2, 3]),
rp: {name: 'Test RP', id: 'example.com'},
user: {
id: new Uint8Array([4, 5, 6]),
name: 'test@example.com',
displayName: 'Test User'
},
pubKeyCredParams: [{type: 'public-key', alg: -7}],
...options
})),
isUserVerifyingPlatformAuthenticatorAvailable: jest.fn().mockResolvedValue(true),
isConditionalMediationAvailable: jest.fn().mockResolvedValue(true)
}
// Mock product API calls that may be triggered by components in the provider tree
global.server.use(
rest.get('*/products*', (req, res, ctx) => {
return res(ctx.delay(0), ctx.status(200), ctx.json({data: []}))
})
)
})
afterEach(() => {
delete global.PublicKeyCredential
})
describe('Rendering', () => {
test('renders modal when isOpen is true', () => {
renderWithProviders(<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />, {
wrapperProps: {appConfig: mockConfig.app}
})
expect(screen.getByText('Create Passkey')).toBeInTheDocument()
expect(screen.getByText(/Passkey Nickname/)).toBeInTheDocument()
expect(
screen.getByPlaceholderText("e.g., 'iPhone', 'Personal Laptop'")
).toBeInTheDocument()
expect(screen.getByText('Register Passkey')).toBeInTheDocument()
})
test('does not render modal when isOpen is false', () => {
renderWithProviders(<PasskeyRegistrationModal isOpen={false} onClose={mockOnClose} />)
expect(screen.queryByText('Create Passkey')).not.toBeInTheDocument()
})
})
describe('User Interactions', () => {
test('allows user to type in nickname input', async () => {
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />
)
const input = screen.getByPlaceholderText("e.g., 'iPhone', 'Personal Laptop'")
await user.type(input, 'My iPhone')
expect(input).toHaveValue('My iPhone')
})
test('calls onClose when close button is clicked', async () => {
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />
)
const closeButton = screen.getByLabelText('Close passkey form')
await user.click(closeButton)
expect(mockOnClose).toHaveBeenCalledTimes(1)
})
test('resets form state when modal opens', async () => {
const {user} = renderWithProviders(<PasskeyRegistrationModalWrapper />)
const input = screen.getByPlaceholderText("e.g., 'iPhone', 'Personal Laptop'")
await user.type(input, 'Test Nickname')
expect(input).toHaveValue('Test Nickname')
// Close modal
const closeButton = screen.getByTestId('passkey-registration-modal-close-button')
await user.click(closeButton)
await waitFor(() => {
expect(
screen.queryByPlaceholderText("e.g., 'iPhone', 'Personal Laptop'")
).not.toBeInTheDocument()
})
// Reopen modal - state should be reset
renderWithProviders(<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />)
const newInput = screen.getByPlaceholderText("e.g., 'iPhone', 'Personal Laptop'")
expect(newInput).toHaveValue('')
})
})
describe('Passkey Registration', () => {
test('calls authorizeWebauthnRegistration on register button click', async () => {
mockMutateAsync.mockResolvedValue({})
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />
)
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(mockMutateAsync).toHaveBeenCalledWith({
user_id: 'test@example.com',
mode: 'callback',
callback_uri: 'https://webhook.site/ee47be40-e9fc-4313-8b56-18e4fe819043'
})
})
})
test('closes modal and opens OTP auth modal on successful registration', async () => {
mockMutateAsync.mockResolvedValue({})
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />
)
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(mockOnClose).toHaveBeenCalled()
expect(screen.getByTestId('otp-auth-modal')).toBeInTheDocument()
})
})
test('displays error message when registration fails', async () => {
const errorMessage = 'Registration failed'
mockMutateAsync.mockRejectedValue(new Error(errorMessage))
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />
)
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(screen.getByText(errorMessage)).toBeInTheDocument()
})
})
test('shows loading state during registration', async () => {
mockMutateAsync.mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 100))
)
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />
)
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
expect(screen.getByText('Registering...')).toBeInTheDocument()
expect(registerButton).toBeDisabled()
})
})
describe('handleOtpVerification', () => {
let mockStartWebauthnRegistration
let mockFinishWebauthnRegistration
let mockAuthorizeWebauthnRegistration
beforeEach(() => {
// Setup separate mocks for each auth helper
mockStartWebauthnRegistration = jest.fn()
mockFinishWebauthnRegistration = jest.fn()
mockAuthorizeWebauthnRegistration = jest.fn()
mockUseAuthHelper.mockImplementation((helperType) => {
if (helperType === 'StartWebauthnUserRegistration') {
return {mutateAsync: mockStartWebauthnRegistration}
}
if (helperType === 'FinishWebauthnUserRegistration') {
return {mutateAsync: mockFinishWebauthnRegistration}
}
if (helperType === 'AuthorizeWebauthnRegistration') {
return {mutateAsync: mockAuthorizeWebauthnRegistration}
}
return {mutateAsync: mockMutateAsync}
})
})
test('successfully completes OTP verification and passkey registration flow', async () => {
const otpCode = '12345678'
const mockChallenge = 'dGVzdC1jaGFsbGVuZ2U='
const mockUserId = 'dGVzdC11c2VyLWlk'
// Mock startWebauthnUserRegistration response
const mockStartResponse = {
challenge: mockChallenge,
rp: {
name: 'Test RP',
id: 'example.com'
},
user: {
id: mockUserId,
name: 'test@example.com',
displayName: 'Test User'
},
pubKeyCredParams: [
{
type: 'public-key',
alg: -7
}
],
authenticatorSelection: {
authenticatorAttachment: 'platform',
userVerification: 'required'
},
timeout: 60000,
attestation: 'none'
}
// Mock WebAuthn credential
const mockCredential = {
type: 'public-key',
id: 'test-credential-id',
rawId: new ArrayBuffer(8),
response: {
attestationObject: new ArrayBuffer(16),
clientDataJSON: new ArrayBuffer(16)
}
}
mockStartWebauthnRegistration.mockResolvedValue(mockStartResponse)
global.navigator.credentials.create.mockResolvedValue(mockCredential)
mockFinishWebauthnRegistration.mockResolvedValue({})
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />,
{
wrapperProps: {appConfig: mockConfig.app}
}
)
// Open OTP modal first
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(screen.getByTestId('otp-auth-modal')).toBeInTheDocument()
})
// Wait for handler to be set
await waitFor(() => {
expect(otpVerificationHandler).toBeTruthy()
})
// Call handleOtpVerification
const result = await otpVerificationHandler(otpCode)
// Verify startWebauthnUserRegistration was called correctly
expect(mockStartWebauthnRegistration).toHaveBeenCalledWith({
user_id: 'test@example.com',
pwd_action_token: otpCode
})
// Verify navigator.credentials.create was called
expect(global.navigator.credentials.create).toHaveBeenCalled()
const publicKeyOptions = global.navigator.credentials.create.mock.calls[0][0].publicKey
// Verify structure and key properties
expect(publicKeyOptions.challenge).toBeDefined()
expect(publicKeyOptions.rp).toMatchObject({
name: 'Test RP',
id: 'example.com'
})
expect(publicKeyOptions.user.id).toBeDefined()
expect(Array.isArray(publicKeyOptions.pubKeyCredParams)).toBe(true)
expect(publicKeyOptions.authenticatorSelection).toBeDefined()
expect(typeof publicKeyOptions.timeout).toBe('number')
expect(publicKeyOptions.attestation).toBe('none')
// Verify finishWebauthnUserRegistration was called correctly
expect(mockFinishWebauthnRegistration).toHaveBeenCalledWith({
username: 'test@example.com',
credential: expect.objectContaining({
type: 'public-key',
id: 'test-credential-id'
}),
pwd_action_token: otpCode
})
// Verify success result
expect(result).toEqual({success: true})
// Verify modals are closed
await waitFor(() => {
expect(mockOnClose).toHaveBeenCalled()
})
})
test('includes nickname in startWebauthnUserRegistration when provided', async () => {
const otpCode = '12345678'
const nickname = 'My iPhone'
const mockStartResponse = {
challenge: 'dGVzdA==',
rp: {name: 'Test', id: 'example.com'},
user: {id: 'dGVzdA==', name: 'test@example.com'},
pubKeyCredParams: [],
timeout: 60000
}
const mockCredential = {
type: 'public-key',
id: 'test-id',
rawId: new ArrayBuffer(8),
response: {
attestationObject: new ArrayBuffer(16),
clientDataJSON: new ArrayBuffer(16)
}
}
mockStartWebauthnRegistration.mockResolvedValue(mockStartResponse)
global.navigator.credentials.create.mockResolvedValue(mockCredential)
mockFinishWebauthnRegistration.mockResolvedValue({})
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />,
{
wrapperProps: {appConfig: mockConfig.app}
}
)
// Set nickname
const input = screen.getByPlaceholderText("e.g., 'iPhone', 'Personal Laptop'")
await user.type(input, nickname)
// Open OTP modal
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(otpVerificationHandler).toBeTruthy()
})
await otpVerificationHandler(otpCode)
// Verify nickname was included
expect(mockStartWebauthnRegistration).toHaveBeenCalledWith({
user_id: 'test@example.com',
pwd_action_token: otpCode,
nick_name: nickname
})
})
test('returns error when startWebauthnUserRegistration fails', async () => {
const otpCode = '12345678'
const errorMessage = 'Failed to start registration'
mockStartWebauthnRegistration.mockRejectedValue(new Error(errorMessage))
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />,
{
wrapperProps: {appConfig: mockConfig.app}
}
)
// Open OTP modal
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(otpVerificationHandler).toBeTruthy()
})
const result = await otpVerificationHandler(otpCode)
expect(result).toEqual({
success: false,
error: errorMessage
})
// Verify modals are not closed on error
// mockOnClose was called once when opening OTP modal, but not again after error
expect(mockOnClose).toHaveBeenCalledTimes(1)
})
test('returns error when WebAuthn API is not available', async () => {
const otpCode = '12345678'
const mockStartResponse = {
challenge: 'dGVzdA==',
rp: {name: 'Test', id: 'example.com'},
user: {id: 'dGVzdA==', name: 'test@example.com'},
pubKeyCredParams: [],
timeout: 60000
}
mockStartWebauthnRegistration.mockResolvedValue(mockStartResponse)
// Remove credentials API
delete global.navigator.credentials
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />,
{
wrapperProps: {appConfig: mockConfig.app}
}
)
// Open OTP modal
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(otpVerificationHandler).toBeTruthy()
})
const result = await otpVerificationHandler(otpCode)
expect(result).toEqual({
success: false,
error: 'WebAuthn API not available in this browser'
})
})
test('returns error when user cancels WebAuthn prompt', async () => {
const otpCode = '12345678'
const mockStartResponse = {
challenge: 'dGVzdA==',
rp: {name: 'Test', id: 'example.com'},
user: {id: 'dGVzdA==', name: 'test@example.com'},
pubKeyCredParams: [],
timeout: 60000
}
const notAllowedError = new Error('User cancelled')
notAllowedError.name = 'NotAllowedError'
mockStartWebauthnRegistration.mockResolvedValue(mockStartResponse)
global.navigator.credentials.create.mockRejectedValue(notAllowedError)
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />,
{
wrapperProps: {appConfig: mockConfig.app}
}
)
// Open OTP modal
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(otpVerificationHandler).toBeTruthy()
})
const result = await otpVerificationHandler(otpCode)
expect(result).toEqual({
success: false,
error: 'Passkey registration was cancelled or timed out'
})
})
test('returns error when WebAuthn create returns null credential', async () => {
const otpCode = '12345678'
const mockStartResponse = {
challenge: 'dGVzdA==',
rp: {name: 'Test', id: 'example.com'},
user: {id: 'dGVzdA==', name: 'test@example.com'},
pubKeyCredParams: [],
timeout: 60000
}
mockStartWebauthnRegistration.mockResolvedValue(mockStartResponse)
global.navigator.credentials.create.mockResolvedValue(null)
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />,
{
wrapperProps: {appConfig: mockConfig.app}
}
)
// Open OTP modal
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(otpVerificationHandler).toBeTruthy()
})
const result = await otpVerificationHandler(otpCode)
expect(result).toEqual({
success: false,
error: 'Failed to create credential: user cancelled or operation failed'
})
})
test('returns error when finishWebauthnUserRegistration fails', async () => {
const otpCode = '12345678'
const mockStartResponse = {
challenge: 'dGVzdA==',
rp: {name: 'Test', id: 'example.com'},
user: {id: 'dGVzdA==', name: 'test@example.com'},
pubKeyCredParams: [],
timeout: 60000
}
const mockCredential = {
type: 'public-key',
id: 'test-id',
rawId: new ArrayBuffer(8),
response: {
attestationObject: new ArrayBuffer(16),
clientDataJSON: new ArrayBuffer(16)
}
}
const errorMessage = 'Failed to finish registration'
mockStartWebauthnRegistration.mockResolvedValue(mockStartResponse)
global.navigator.credentials.create.mockResolvedValue(mockCredential)
mockFinishWebauthnRegistration.mockRejectedValue(new Error(errorMessage))
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />,
{
wrapperProps: {appConfig: mockConfig.app}
}
)
// Open OTP modal
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(otpVerificationHandler).toBeTruthy()
})
const result = await otpVerificationHandler(otpCode)
expect(result).toEqual({
success: false,
error: errorMessage
})
})
test('handles AbortError from WebAuthn API', async () => {
const otpCode = '12345678'
const mockStartResponse = {
challenge: 'dGVzdA==',
rp: {name: 'Test', id: 'example.com'},
user: {id: 'dGVzdA==', name: 'test@example.com'},
pubKeyCredParams: [],
timeout: 60000
}
const abortError = new Error('Operation aborted')
abortError.name = 'AbortError'
mockStartWebauthnRegistration.mockResolvedValue(mockStartResponse)
global.navigator.credentials.create.mockRejectedValue(abortError)
const {user} = renderWithProviders(
<PasskeyRegistrationModal isOpen={true} onClose={mockOnClose} />,
{
wrapperProps: {appConfig: mockConfig.app}
}
)
// Open OTP modal
const registerButton = screen.getByText('Register Passkey')
await user.click(registerButton)
await waitFor(() => {
expect(otpVerificationHandler).toBeTruthy()
})
const result = await otpVerificationHandler(otpCode)
expect(result).toEqual({
success: false,
error: 'Passkey registration was cancelled or timed out'
})
})
})
})