-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathone-click-user-registration.test.js
More file actions
417 lines (384 loc) · 17.9 KB
/
one-click-user-registration.test.js
File metadata and controls
417 lines (384 loc) · 17.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
/*
* Copyright (c) 2025, Salesforce, 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 {IntlProvider} from 'react-intl'
import {render, screen, waitFor} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import UserRegistration from '@salesforce/retail-react-app/app/pages/checkout-one-click/partials/one-click-user-registration'
import {useCurrentBasket} from '@salesforce/retail-react-app/app/hooks/use-current-basket'
import {useCustomerType} from '@salesforce/commerce-sdk-react'
import useAuthContext from '@salesforce/commerce-sdk-react/hooks/useAuthContext'
jest.mock('@salesforce/retail-react-app/app/hooks/use-current-basket')
const {AuthHelpers} = jest.requireActual('@salesforce/commerce-sdk-react')
const TEST_MESSAGES = {
'checkout.title.user_registration': 'Save Checkout Info for Future Use',
'checkout.label.user_registration': 'Create an account to check out faster',
'checkout.message.user_registration':
'Your payment, address, and contact information will be saved in a new account.'
}
const mockAuthHelperFunctions = {
[AuthHelpers.AuthorizePasswordless]: {mutateAsync: jest.fn()},
[AuthHelpers.LoginPasswordlessUser]: {mutateAsync: jest.fn()}
}
jest.mock('@salesforce/commerce-sdk-react', () => {
const original = jest.requireActual('@salesforce/commerce-sdk-react')
return {
...original,
useCustomerType: jest.fn(),
useAuthHelper: jest.fn((helper) => mockAuthHelperFunctions[helper])
}
})
jest.mock('@salesforce/commerce-sdk-react/hooks/useAuthContext', () =>
jest.fn(() => ({refreshAccessToken: jest.fn().mockResolvedValue(undefined)}))
)
jest.mock('@salesforce/retail-react-app/app/components/otp-auth', () => {
// eslint-disable-next-line react/prop-types
const MockOtpAuth = function ({isOpen, handleOtpVerification, onClose, isGuestRegistration}) {
return isOpen ? (
<>
<div data-testid={isGuestRegistration ? 'otp-guest' : 'otp-returning'} />
<button onClick={() => handleOtpVerification('otp-123')} data-testid="otp-verify">
Verify OTP
</button>
<button onClick={onClose} data-testid="otp-close">
Close
</button>
</>
) : null
}
return MockOtpAuth
})
jest.mock('@salesforce/retail-react-app/app/hooks/use-app-origin', () => ({
useAppOrigin: () => 'http://localhost:3000'
}))
jest.mock('@salesforce/pwa-kit-runtime/utils/ssr-config', () => ({
getConfig: () => ({app: {login: {passwordless: {callbackURI: '/callback'}}}})
}))
const setup = (overrides = {}) => {
const defaultBasket = {
basketId: 'basket-123',
customerInfo: {email: 'test@example.com'},
productItems: [{productId: 'sku-1', quantity: 1}],
shipments: [{shippingAddress: {address1: '123 Main'}, shippingMethod: {id: 'Ground'}}]
}
useCurrentBasket.mockReturnValue({data: overrides.basket ?? defaultBasket})
useCustomerType.mockReturnValue({isGuest: overrides.isGuest ?? true})
useAuthContext.mockReturnValue({refreshAccessToken: jest.fn().mockResolvedValue(undefined)})
// Set up specific mock behaviors if provided via overrides
if (overrides.authorizeMutate) {
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync =
overrides.authorizeMutate
} else {
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockResolvedValue({})
}
if (overrides.loginMutate) {
mockAuthHelperFunctions[AuthHelpers.LoginPasswordlessUser].mutateAsync =
overrides.loginMutate
} else {
mockAuthHelperFunctions[AuthHelpers.LoginPasswordlessUser].mutateAsync.mockResolvedValue({})
}
const props = {
enableUserRegistration: overrides.enable ?? false,
setEnableUserRegistration: overrides.setEnable ?? jest.fn(),
isGuestCheckout: overrides.isGuestCheckout ?? false,
isDisabled: overrides.isDisabled ?? false,
onSavePreferenceChange: overrides.onSavePref ?? jest.fn(),
onRegistered: overrides.onRegistered ?? jest.fn()
}
const utils = render(
<IntlProvider locale="en-GB" messages={TEST_MESSAGES}>
<UserRegistration {...props} />
</IntlProvider>
)
return {
utils,
props,
authorizePasswordlessLogin: mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless],
loginPasswordless: mockAuthHelperFunctions[AuthHelpers.LoginPasswordlessUser]
}
}
describe('UserRegistration', () => {
beforeEach(() => {
jest.clearAllMocks()
})
test('opt-in triggers save preference and opens OTP for guest', async () => {
const user = userEvent.setup()
const {props, authorizePasswordlessLogin} = setup()
// Toggle on
await user.click(screen.getByRole('checkbox', {name: /Create an account/i}))
expect(props.setEnableUserRegistration).toHaveBeenCalledWith(true)
expect(props.onSavePreferenceChange).toHaveBeenCalledWith(true)
// Verify authorize passwordless was called
await waitFor(() => {
expect(authorizePasswordlessLogin.mutateAsync).toHaveBeenCalledWith({
userid: 'test@example.com',
callbackURI: 'http://localhost:3000/callback?mode=otp_email',
register_customer: true,
last_name: 'test@example.com',
email: 'test@example.com'
})
})
// Guest registration OTP modal should render with guest flag
expect(await screen.findByTestId('otp-guest')).toBeInTheDocument()
// Modal appears (mocked), verify OTP triggers onRegistered callback
const otpButton = await screen.findByTestId('otp-verify')
await user.click(otpButton)
await waitFor(() => {
expect(props.onRegistered).toHaveBeenCalledWith('basket-123')
})
})
test('does not send OTP when shopper is not a guest', async () => {
const user = userEvent.setup()
const {authorizePasswordlessLogin} = setup({isGuest: false})
await user.click(screen.getByRole('checkbox', {name: /Create an account/i}))
expect(authorizePasswordlessLogin.mutateAsync).not.toHaveBeenCalled()
})
test('toggling off updates save preference', async () => {
const user = userEvent.setup()
// Start with enabled, then toggle off
const {props} = setup({enable: true})
const cb = screen.getByRole('checkbox', {name: /Create an account/i})
expect(cb).toBeChecked()
await user.click(cb) // off
expect(props.onSavePreferenceChange).toHaveBeenCalledWith(false)
})
test('hides component when isGuestCheckout is true', () => {
setup({isGuestCheckout: true})
expect(screen.queryByTestId('sf-user-registration-content')).not.toBeInTheDocument()
})
test('renders component when isGuestCheckout is false', () => {
setup({isGuestCheckout: false})
expect(screen.getByTestId('sf-user-registration-content')).toBeInTheDocument()
})
test('disables checkbox when isDisabled is true', () => {
setup({isDisabled: true})
const checkbox = screen.getByRole('checkbox', {name: /Create an account/i})
expect(checkbox).toBeDisabled()
})
test('does not send OTP when basket has no email', async () => {
const user = userEvent.setup()
const basketWithoutEmail = {
basketId: 'basket-123',
customerInfo: {},
productItems: [{productId: 'sku-1', quantity: 1}]
}
const {authorizePasswordlessLogin} = setup({basket: basketWithoutEmail})
await user.click(screen.getByRole('checkbox', {name: /Create an account/i}))
expect(authorizePasswordlessLogin.mutateAsync).not.toHaveBeenCalled()
})
test('does not send OTP when basket customerInfo is undefined', async () => {
const user = userEvent.setup()
const basketWithoutCustomerInfo = {
basketId: 'basket-123',
productItems: [{productId: 'sku-1', quantity: 1}]
}
const {authorizePasswordlessLogin} = setup({basket: basketWithoutCustomerInfo})
await user.click(screen.getByRole('checkbox', {name: /Create an account/i}))
expect(authorizePasswordlessLogin.mutateAsync).not.toHaveBeenCalled()
})
test('handles authorize passwordless error gracefully', async () => {
const user = userEvent.setup()
const authorizeMutate = jest.fn().mockRejectedValue(new Error('Network error'))
const {props} = setup({authorizeMutate})
await user.click(screen.getByRole('checkbox', {name: /Create an account/i}))
expect(props.setEnableUserRegistration).toHaveBeenCalledWith(true)
// Should not throw error, component continues to work
expect(screen.getByRole('checkbox', {name: /Create an account/i})).toBeInTheDocument()
})
test('blocks duplicate OTP sends until reset', async () => {
const user = userEvent.setup()
const {authorizePasswordlessLogin} = setup()
const checkbox = screen.getByRole('checkbox', {name: /Create an account/i})
// Click to enable
await user.click(checkbox)
await waitFor(() => {
expect(authorizePasswordlessLogin.mutateAsync).toHaveBeenCalledTimes(1)
})
// Click to enable again without unchecking/closing — should not send again
await user.click(checkbox)
expect(authorizePasswordlessLogin.mutateAsync).toHaveBeenCalledTimes(1)
})
test('re-sends OTP after modal close and retry', async () => {
const user = userEvent.setup()
// Arrange mocks without rendering via setup()
const defaultBasket = {
basketId: 'basket-123',
customerInfo: {email: 'test@example.com'},
productItems: [{productId: 'sku-1', quantity: 1}],
shipments: [{shippingAddress: {address1: '123 Main'}, shippingMethod: {id: 'Ground'}}]
}
useCurrentBasket.mockReturnValue({data: defaultBasket})
useCustomerType.mockReturnValue({isGuest: true})
const authorizePasswordlessLogin =
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless]
authorizePasswordlessLogin.mutateAsync.mockResolvedValue({})
// Wrapper to control the enableUserRegistration prop to simulate real toggling
const Stateful = () => {
const [enabled, setEnabled] = React.useState(false)
return (
<IntlProvider locale="en-GB" messages={TEST_MESSAGES}>
<UserRegistration
enableUserRegistration={enabled}
setEnableUserRegistration={(val) => setEnabled(val)}
isGuestCheckout={false}
isDisabled={false}
onSavePreferenceChange={jest.fn()}
onRegistered={jest.fn()}
/>
</IntlProvider>
)
}
render(<Stateful />)
const checkbox = screen.getByRole('checkbox', {name: /Create an account/i})
// First enable triggers OTP send and opens modal
await user.click(checkbox) // enable -> true
await waitFor(() => {
expect(screen.getByTestId('otp-guest')).toBeInTheDocument()
})
expect(authorizePasswordlessLogin.mutateAsync).toHaveBeenCalledTimes(1)
// Close the modal (this should reset the guard)
await user.click(screen.getByTestId('otp-close'))
// Toggle off then on to re-enable
await user.click(checkbox) // disable -> false
await user.click(checkbox) // enable -> true
// Should send OTP again after close + re-enable
await waitFor(() => {
expect(authorizePasswordlessLogin.mutateAsync).toHaveBeenCalledTimes(2)
})
})
test('re-sends OTP after uncheck and re-check', async () => {
const user = userEvent.setup()
// Arrange mocks without rendering via setup()
const defaultBasket = {
basketId: 'basket-123',
customerInfo: {email: 'test@example.com'},
productItems: [{productId: 'sku-1', quantity: 1}],
shipments: [{shippingAddress: {address1: '123 Main'}, shippingMethod: {id: 'Ground'}}]
}
useCurrentBasket.mockReturnValue({data: defaultBasket})
useCustomerType.mockReturnValue({isGuest: true})
const authorizePasswordlessLogin =
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless]
authorizePasswordlessLogin.mutateAsync.mockResolvedValue({})
// Wrapper to control the enableUserRegistration prop to simulate real toggling
const Stateful = () => {
const [enabled, setEnabled] = React.useState(false)
return (
<IntlProvider locale="en-GB" messages={TEST_MESSAGES}>
<UserRegistration
enableUserRegistration={enabled}
setEnableUserRegistration={(val) => setEnabled(val)}
isGuestCheckout={false}
isDisabled={false}
onSavePreferenceChange={jest.fn()}
onRegistered={jest.fn()}
/>
</IntlProvider>
)
}
render(<Stateful />)
const checkbox = screen.getByRole('checkbox', {name: /Create an account/i})
// Enable -> first send
await user.click(checkbox) // enable -> true
await waitFor(() => {
expect(authorizePasswordlessLogin.mutateAsync).toHaveBeenCalledTimes(1)
})
// Uncheck
await user.click(checkbox) // disable -> false
// Re-check -> should send again due to guard reset on uncheck
await user.click(checkbox) // enable -> true
await waitFor(() => {
expect(authorizePasswordlessLogin.mutateAsync).toHaveBeenCalledTimes(2)
})
})
test('OTP resend functionality works', async () => {
const user = userEvent.setup()
const {authorizePasswordlessLogin} = setup()
await user.click(screen.getByRole('checkbox', {name: /Create an account/i}))
await waitFor(() => {
expect(screen.getByTestId('otp-guest')).toBeInTheDocument()
})
// Initial authorize call
expect(authorizePasswordlessLogin.mutateAsync).toHaveBeenCalledTimes(1)
})
test('shows account creation notification after successful OTP verification', async () => {
const user = userEvent.setup()
setup()
// Enable registration to trigger OTP
await user.click(screen.getByRole('checkbox', {name: /Create an account/i}))
// Verify OTP (mocked)
const otpButton = await screen.findByTestId('otp-verify')
await user.click(otpButton)
// Notification should appear after registration succeeds
await waitFor(() => {
expect(screen.getByTestId('sf-account-creation-notification')).toBeInTheDocument()
})
// Optional: assert key content
expect(screen.getByText(/Account Created/i)).toBeInTheDocument()
// Use aria-label to avoid ambiguity with body text containing 'verified'
expect(screen.getByLabelText(/Verified/i)).toBeInTheDocument()
})
test('renders account creation notification when showNotice prop is true', async () => {
render(
<IntlProvider locale="en-GB">
<UserRegistration
enableUserRegistration={false}
setEnableUserRegistration={jest.fn()}
isGuestCheckout={false}
isDisabled={false}
onSavePreferenceChange={jest.fn()}
onRegistered={jest.fn()}
showNotice
/>
</IntlProvider>
)
expect(screen.getByTestId('sf-account-creation-notification')).toBeInTheDocument()
expect(screen.getByText(/Account Created/i)).toBeInTheDocument()
})
test('calls loginPasswordless with OTP code and register flag', async () => {
const user = userEvent.setup()
const {loginPasswordless} = setup()
await user.click(screen.getByRole('checkbox', {name: /Create an account/i}))
const otpButton = await screen.findByTestId('otp-verify')
await user.click(otpButton)
await waitFor(() => {
expect(loginPasswordless.mutateAsync).toHaveBeenCalledWith({
pwdlessLoginToken: 'otp-123',
register_customer: true
})
})
})
test('handles OTP verification error gracefully', async () => {
const user = userEvent.setup()
const loginMutate = jest.fn().mockRejectedValue(new Error('Invalid OTP'))
const {props} = setup({loginMutate})
await user.click(screen.getByRole('checkbox', {name: /Create an account/i}))
const otpButton = await screen.findByTestId('otp-verify')
await user.click(otpButton)
// Wait for async operations
await waitFor(() => {
expect(loginMutate).toHaveBeenCalled()
})
// onRegistered should not be called on error
expect(props.onRegistered).not.toHaveBeenCalled()
})
test('displays explanatory text when registration is enabled', () => {
// Test with registration disabled
const {utils} = setup({enable: false})
expect(
screen.queryByText(/Your payment, address, and contact information/i)
).not.toBeInTheDocument()
// Clean up first render
utils.unmount()
// Test with registration enabled
setup({enable: true})
expect(
screen.getByText(/Your payment, address, and contact information/i)
).toBeInTheDocument()
})
})
// end