-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathuse-auth-modal.test.js
More file actions
475 lines (413 loc) · 18.8 KB
/
use-auth-modal.test.js
File metadata and controls
475 lines (413 loc) · 18.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
/*
* Copyright (c) 2022, 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 PropTypes from 'prop-types'
import {screen, within, waitFor} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {
renderWithProviders,
createPathWithDefaults,
guestToken
} from '@salesforce/retail-react-app/app/utils/test-utils'
import {AuthModal, useAuthModal} from '@salesforce/retail-react-app/app/hooks/use-auth-modal'
import {BrowserRouter as Router, Route} from 'react-router-dom'
import Account from '@salesforce/retail-react-app/app/pages/account'
import {rest} from 'msw'
import {mockedRegisteredCustomer} from '@salesforce/retail-react-app/app/mocks/mock-data'
import * as ReactHookForm from 'react-hook-form'
import {AuthHelpers} from '@salesforce/commerce-sdk-react'
jest.setTimeout(60000)
const mockMergedBasket = {
basketId: 'a10ff320829cb0eef93ca5310a',
currency: 'USD',
customerInfo: {
customerId: 'registeredCustomerId',
email: 'customer@test.com'
}
}
const mockPasswordToken = {
email: 'foo@test.com',
expiresInMinutes: 10,
login: 'foo@test.com',
resetToken: 'testresettoken'
}
const mockRegisteredCustomer = {
authType: 'registered',
customerId: 'registeredCustomerId',
customerNo: 'testno',
email: 'customer@test.com',
firstName: 'Tester',
lastName: 'Testing',
login: 'customer@test.com'
}
const mockAuthHelperFunctions = {
[AuthHelpers.AuthorizePasswordless]: {mutateAsync: jest.fn()},
[AuthHelpers.Register]: {mutateAsync: jest.fn()}
}
jest.mock('@salesforce/commerce-sdk-react', () => {
const originalModule = jest.requireActual('@salesforce/commerce-sdk-react')
return {
...originalModule,
useAuthHelper: jest
.fn()
.mockImplementation((helperType) => mockAuthHelperFunctions[helperType])
}
})
let authModal = undefined
const MockedComponent = (props) => {
const {initialView, isPasswordlessEnabled = false} = props
authModal = useAuthModal(initialView || undefined)
const match = {
params: {pageName: 'profile'}
}
return (
<Router>
<button onClick={authModal.onOpen}>Open Modal</button>
<AuthModal {...authModal} isPasswordlessEnabled={isPasswordlessEnabled} />
<Route path={createPathWithDefaults('/account')}>
<Account match={match} />
</Route>
</Router>
)
}
MockedComponent.propTypes = {
initialView: PropTypes.string,
isPasswordlessEnabled: PropTypes.bool
}
// Set up and clean up
beforeEach(() => {
authModal = undefined
global.server.use(
rest.post('*/customers', (req, res, ctx) => {
return res(ctx.delay(0), ctx.status(200), ctx.json(mockRegisteredCustomer))
}),
rest.get('*/customers/:customerId', (req, res, ctx) => {
return res(ctx.delay(0), ctx.status(200), ctx.json(mockRegisteredCustomer))
}),
rest.post('*/customers/password/actions/create-reset-token', (req, res, ctx) => {
return res(ctx.delay(0), ctx.status(200), ctx.json(mockPasswordToken))
}),
rest.post('*/oauth2/token', (req, res, ctx) =>
res(
ctx.delay(0),
ctx.json({
customer_id: 'customerid',
access_token: guestToken,
refresh_token: 'testrefeshtoken',
usid: 'testusid',
enc_user_id: 'testEncUserId',
id_token: 'testIdToken'
})
)
),
rest.post('*/baskets/actions/merge', (req, res, ctx) => {
return res(ctx.delay(0), ctx.json(mockMergedBasket))
})
)
})
afterEach(() => {
localStorage.clear()
jest.resetModules()
})
test('Renders login modal by default', async () => {
const user = userEvent.setup()
renderWithProviders(<MockedComponent />)
// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)
await waitFor(() => {
expect(screen.getByText(/welcome back/i)).toBeInTheDocument()
expect(screen.getByLabelText(/email/i)).toBeInTheDocument()
expect(screen.getByLabelText(/Password/)).toBeInTheDocument()
expect(screen.getByText(/forgot password/i)).toBeInTheDocument()
expect(screen.getByText(/sign in/i)).toBeInTheDocument()
})
})
test('Renders check email modal on email mode', async () => {
// Store the original useForm function
const originalUseForm = ReactHookForm.useForm
// Spy on useForm
const mockUseForm = jest.spyOn(ReactHookForm, 'useForm').mockImplementation((...args) => {
// Call the original useForm
const methods = originalUseForm(...args)
// Override only formState
return {
...methods,
formState: {
...methods.formState,
isSubmitSuccessful: true // Set to true to render the Check Your Email modal
}
}
})
const user = userEvent.setup()
renderWithProviders(<MockedComponent initialView="email" />)
// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)
await waitFor(() => {
expect(screen.getByText(/check your email/i)).toBeInTheDocument()
})
mockUseForm.mockRestore()
})
describe('Passwordless enabled', () => {
test('Renders passwordless login when enabled', async () => {
const user = userEvent.setup()
renderWithProviders(<MockedComponent isPasswordlessEnabled={true} />)
// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)
await waitFor(() => {
expect(screen.getByText(/continue securely/i)).toBeInTheDocument()
})
})
test('Allows passwordless login', async () => {
const {user} = renderWithProviders(<MockedComponent isPasswordlessEnabled={true} />)
const validEmail = 'test@salesforce.com'
// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)
await waitFor(() => {
expect(screen.getByText(/continue securely/i)).toBeInTheDocument()
})
// enter a valid email address
await user.type(screen.getByLabelText('Email'), validEmail)
// initiate passwordless login
const passwordlessLoginButton = screen.getByText(/continue securely/i)
// Click the button twice as the isPasswordlessLoginClicked state doesn't change after the first click
await user.click(passwordlessLoginButton)
await user.click(passwordlessLoginButton)
expect(
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync
).toHaveBeenCalledWith({
userid: validEmail,
callbackURI: 'https://webhook.site/27761b71-50c1-4097-a600-21a3b89a546c?redirectUrl=/'
})
// check that check email modal is open
await waitFor(() => {
const withinForm = within(screen.getByTestId('sf-form-resend-passwordless-email'))
expect(withinForm.getByText(/Check Your Email/i)).toBeInTheDocument()
expect(withinForm.getByText(validEmail)).toBeInTheDocument()
})
// resend the email
user.click(screen.getByText(/Resend Link/i))
expect(
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync
).toHaveBeenCalledWith({
userid: validEmail,
callbackURI: 'https://webhook.site/27761b71-50c1-4097-a600-21a3b89a546c?redirectUrl=/'
})
})
})
// TODO: Fix flaky/broken test
// eslint-disable-next-line jest/no-disabled-tests
test.skip('Renders error when given incorrect log in credentials', async () => {
const user = userEvent.setup()
// render our test component
renderWithProviders(<MockedComponent />, {
wrapperProps: {
bypassAuth: false
}
})
// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)
// enter credentials and submit
await user.type(screen.getByLabelText('Email'), 'bad@test.com')
await user.type(screen.getByLabelText('Password'), 'SomeFakePassword1!')
// mock failed auth request
global.server.use(
rest.post('*/oauth2/login', (req, res, ctx) =>
res(ctx.delay(0), ctx.status(401), ctx.json({message: 'Unauthorized Credentials.'}))
),
rest.post('*/customers', (req, res, ctx) => {
return res(ctx.delay(0), ctx.status(404), ctx.json({message: 'Not Found.'}))
})
)
await user.click(screen.getByText(/sign in/i))
// give it some time to show the error in the form
await waitFor(
() => {
// wait for login error alert to appear
expect(
screen.getByText(/something's not right with your email or password\. try again\./i)
).toBeInTheDocument()
},
{
timeout: 10000
}
)
})
test('Allows customer to create an account', async () => {
const user = userEvent.setup()
// render our test component
renderWithProviders(<MockedComponent />, {
wrapperProps: {
bypassAuth: true
}
})
// open the modal
const trigger = screen.getByText('Open Modal')
await user.click(trigger)
let form
await waitFor(() => {
form = screen.queryByTestId('sf-auth-modal-form')
expect(form).toBeInTheDocument()
})
const createAccount = screen.getByText(/create account/i)
await user.click(createAccount)
let registerForm
await waitFor(() => {
registerForm = screen.getByTestId('sf-auth-modal-form-register')
expect(registerForm).toBeInTheDocument()
})
const withinForm = within(registerForm)
// fill out form and submit
await waitFor(() => {
const firstName = withinForm.getByLabelText(/First Name/i)
expect(firstName).toBeInTheDocument()
})
await user.type(withinForm.getByLabelText('First Name'), 'Tester')
await user.type(withinForm.getByLabelText('Last Name'), 'Tester')
await user.type(withinForm.getByPlaceholderText(/you@email.com/i), 'customer@test.com')
await user.type(withinForm.getAllByLabelText(/password/i)[0], 'Password!1')
// login with credentials
global.server.use(
rest.post('*/oauth2/token', (req, res, ctx) => {
return res(
ctx.delay(0),
ctx.json({
customer_id: 'customerid_1',
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FmZS1hM2M1LTc1NjIzMjY1MmZmNSIsImN0eCI6InNsYXMiLCJpc3MiOiJzbGFzL3Byb2QvenpyZl8wMDEiLCJpc3QiOjEsImF1ZCI6ImNvbW1lcmNlY2xvdWQvcHJvZC96enJmXzAwMSIsIm5iZiI6MTY3ODgzNDI3MSwic3R5IjoiVXNlciIsImlzYiI6InVpZG86ZWNvbTo6dXBuOmtldjVAdGVzdC5jb206OnVpZG46a2V2aW4gaGU6OmdjaWQ6YWJtZXMybWJrM2xYa1JsSEZKd0dZWWt1eEo6OnJjaWQ6YWJVTXNhdnBEOVk2alcwMGRpMlNqeEdDTVU6OmNoaWQ6UmVmQXJjaEdsb2JhbCIsImV4cCI6MjY3ODgzNjEwMSwiaWF0IjoxNjc4ODM0MzAxLCJqdGkiOiJDMkM0ODU2MjAxODYwLTE4OTA2Nzg5MDM0ODA1ODMyNTcwNjY2NTQyIn0._tUrxeXdFYPj6ZoY-GILFRd3-aD1RGPkZX6TqHeS494',
refresh_token: 'testrefeshtoken_1',
usid: 'testusid_1',
enc_user_id: 'testEncUserId_1',
id_token: 'testIdToken_1'
})
)
}),
rest.post('*/oauth2/login', (req, res, ctx) => {
return res(ctx.delay(0), ctx.status(200), ctx.json(mockedRegisteredCustomer))
}),
rest.get('*/customers/:customerId', (req, res, ctx) => {
return res(ctx.delay(0), ctx.status(200), ctx.json(mockedRegisteredCustomer))
})
)
const submitButton = withinForm.getByText(/create account/i)
await user.click(submitButton)
await waitFor(() => {
expect(form).not.toBeInTheDocument()
})
// wait for success state to appear
await waitFor(
() => {
expect(window.location.pathname).toBe('/uk/en-GB/account')
const myAccount = screen.getAllByText(/My Account/)
expect(myAccount).toHaveLength(2)
},
{
timeout: 5000
}
)
})
// TODO: investingate why this test is failing when running with other tests
// eslint-disable-next-line jest/no-disabled-tests
test.skip('Allows customer to sign in to their account', async () => {
const user = userEvent.setup()
// render our test component
renderWithProviders(<MockedComponent />, {
wrapperProps: {
bypassAuth: false
}
})
// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)
// enter credentials and submit
await user.type(screen.getByLabelText('Email'), 'customer@test.com')
await user.type(screen.getByLabelText('Password'), 'Password!1')
// login with credentials
global.server.use(
rest.post('*/oauth2/token', (req, res, ctx) =>
res(
ctx.delay(0),
ctx.json({
customer_id: 'customerid_1',
access_token:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdXQiOiJHVUlEIiwic2NwIjoic2ZjYy5zaG9wcGVyLW15YWNjb3VudC5iYXNrZXRzIHNmY2Muc2hvcHBlci1teWFjY291bnQuYWRkcmVzc2VzIHNmY2Muc2hvcHBlci1wcm9kdWN0cyBzZmNjLnNob3BwZXItZGlzY292ZXJ5LXNlYXJjaCBzZmNjLnNob3BwZXItbXlhY2NvdW50LnJ3IHNmY2Muc2hvcHBlci1teWFjY291bnQucGF5bWVudGluc3RydW1lbnRzIHNmY2Muc2hvcHBlci1jdXN0b21lcnMubG9naW4gc2ZjYy5zaG9wcGVyLWV4cGVyaWVuY2Ugc2ZjYy5zaG9wcGVyLW15YWNjb3VudC5vcmRlcnMgc2ZjYy5zaG9wcGVyLWN1c3RvbWVycy5yZWdpc3RlciBzZmNjLnNob3BwZXItYmFza2V0cy1vcmRlcnMgc2ZjYy5zaG9wcGVyLW15YWNjb3VudC5hZGRyZXNzZXMucncgc2ZjYy5zaG9wcGVyLW15YWNjb3VudC5wcm9kdWN0bGlzdHMucncgc2ZjYy5zaG9wcGVyLXByb2R1Y3RsaXN0cyBzZmNjLnNob3BwZXItcHJvbW90aW9ucyBzZmNjLnNob3BwZXItYmFza2V0cy1vcmRlcnMucncgc2ZjYy5zaG9wcGVyLW15YWNjb3VudC5wYXltZW50aW5zdHJ1bWVudHMucncgc2ZjYy5zaG9wcGVyLWdpZnQtY2VydGlmaWNhdGVzIHNmY2Muc2hvcHBlci1wcm9kdWN0LXNlYXJjaCBzZmNjLnNob3BwZXItbXlhY2NvdW50LnByb2R1Y3RsaXN0cyBzZmNjLnNob3BwZXItY2F0ZWdvcmllcyBzZmNjLnNob3BwZXItbXlhY2NvdW50Iiwic3ViIjoiY2Mtc2xhczo6enpyZl8wMDE6OnNjaWQ6YzljNDViZmQtMGVkMy00YWEyLTk5NzEtNDBmODg5NjJiODM2Ojp1c2lkOjhlODgzOTczLTY4ZWItNDFmZS1hM2M1LTc1NjIzMjY1MmZmNSIsImN0eCI6InNsYXMiLCJpc3MiOiJzbGFzL3Byb2QvenpyZl8wMDEiLCJpc3QiOjEsImF1ZCI6ImNvbW1lcmNlY2xvdWQvcHJvZC96enJmXzAwMSIsIm5iZiI6MTY3ODgzNDI3MSwic3R5IjoiVXNlciIsImlzYiI6InVpZG86ZWNvbTo6dXBuOmtldjVAdGVzdC5jb206OnVpZG46a2V2aW4gaGU6OmdjaWQ6YWJtZXMybWJrM2xYa1JsSEZKd0dZWWt1eEo6OnJjaWQ6YWJVTXNhdnBEOVk2alcwMGRpMlNqeEdDTVU6OmNoaWQ6UmVmQXJjaEdsb2JhbCIsImV4cCI6MjY3ODgzNjEwMSwiaWF0IjoxNjc4ODM0MzAxLCJqdGkiOiJDMkM0ODU2MjAxODYwLTE4OTA2Nzg5MDM0ODA1ODMyNTcwNjY2NTQyIn0._tUrxeXdFYPj6ZoY-GILFRd3-aD1RGPkZX6TqHeS494',
refresh_token: 'testrefeshtoken_1',
usid: 'testusid_1',
enc_user_id: 'testEncUserId_1',
id_token: 'testIdToken_1'
})
)
)
)
await user.click(screen.getByText(/sign in/i))
// allow time to transition to account page
await waitFor(
() => {
expect(window.location.pathname).toBe('/uk/en-GB/account')
expect(screen.getByText(/My Profile/i)).toBeInTheDocument()
},
{timeout: 5000}
)
})
describe('Reset password', function () {
beforeEach(() => {
global.server.use(
rest.post('*/customers/password/actions/create-reset-token', (req, res, ctx) =>
res(ctx.delay(0), ctx.status(200), ctx.json(mockPasswordToken))
)
)
})
// TODO: Fix flaky/broken test
// eslint-disable-next-line jest/no-disabled-tests
test.skip('Allows customer to generate password token', async () => {
const user = userEvent.setup()
// render our test component
renderWithProviders(<MockedComponent initialView="password" />, {
wrapperProps: {
bypassAuth: false
}
})
// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)
expect(authModal.isOpen).toBe(true)
// enter credentials and submit
// const withinForm = within(screen.getByTestId('sf-auth-modal-form'))
let resetPwForm = await screen.findByTestId('sf-auth-modal-form-reset-pw')
expect(resetPwForm).toBeInTheDocument()
const withinForm = within(resetPwForm)
await user.type(withinForm.getByLabelText('Email'), 'foo@test.com')
await user.click(withinForm.getByText(/reset password/i))
// wait for success state
await waitFor(() => {
expect(screen.getByText(/password reset/i)).toBeInTheDocument()
expect(screen.getByText(/foo@test.com/i)).toBeInTheDocument()
})
})
// TODO: Fix flaky/broken test
// eslint-disable-next-line jest/no-disabled-tests
test.skip('Allows customer to open generate password token modal from everywhere', async () => {
const user = userEvent.setup()
// render our test component
renderWithProviders(<MockedComponent initialView="password" />)
// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)
expect(authModal.isOpen).toBe(true)
const withinForm = within(screen.getByTestId('sf-auth-modal-form'))
expect(withinForm.getByText(/Reset Password/i)).toBeInTheDocument()
// close the modal
const switchToSignIn = screen.getByText(/Sign in/i)
await user.click(switchToSignIn)
// check that the modal is closed
expect(authModal.isOpen).toBe(false)
})
})