-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathindex.test.js
More file actions
427 lines (393 loc) · 17.9 KB
/
index.test.js
File metadata and controls
427 lines (393 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
418
419
420
421
422
423
424
425
426
427
/*
* 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} from '@testing-library/react'
import {rest} from 'msw'
import {
renderWithProviders,
createPathWithDefaults,
guestToken
} from '@salesforce/retail-react-app/app/utils/test-utils'
import Login from '.'
import {BrowserRouter as Router, Route} from 'react-router-dom'
import Account from '@salesforce/retail-react-app/app/pages/account'
import Registration from '@salesforce/retail-react-app/app/pages/registration'
import ResetPassword from '@salesforce/retail-react-app/app/pages/reset-password'
import mockConfig from '@salesforce/retail-react-app/config/mocks/default'
import {mockedRegisteredCustomer} from '@salesforce/retail-react-app/app/mocks/mock-data'
import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config'
import {AuthHelpers} from '@salesforce/commerce-sdk-react'
const mockMergedBasket = {
basketId: 'a10ff320829cb0eef93ca5310a',
currency: 'USD',
customerInfo: {
customerId: 'registeredCustomerId',
email: 'customer@test.com'
}
}
jest.mock('@salesforce/pwa-kit-runtime/utils/ssr-config', () => ({
getConfig: jest.fn()
}))
const mockAuthHelperFunctions = {
[AuthHelpers.AuthorizePasswordless]: {mutateAsync: jest.fn()}
}
jest.mock('@salesforce/commerce-sdk-react', () => {
const originalModule = jest.requireActual('@salesforce/commerce-sdk-react')
return {
...originalModule,
useAuthHelper: jest.fn((helperType) => {
// Return mock for AuthorizePasswordless, real implementation for others
if (mockAuthHelperFunctions[helperType]) {
return mockAuthHelperFunctions[helperType]
}
return originalModule.useAuthHelper(helperType)
})
}
})
const MockedComponent = () => {
const match = {
params: {pageName: 'profile'}
}
return (
<Router>
<Login />
<Route path={createPathWithDefaults('/registration')}>
<Registration />
</Route>
<Route path={createPathWithDefaults('/reset-password')}>
<ResetPassword />
</Route>
<Route path={createPathWithDefaults('/account')}>
<Account match={match} />
</Route>
</Router>
)
}
// Set up and clean up
beforeEach(() => {
jest.resetModules()
getConfig.mockReturnValue(mockConfig)
global.server.use(
rest.post('*/customers', (req, res, ctx) => {
return res(ctx.delay(0), ctx.status(200), ctx.json(mockedRegisteredCustomer))
}),
rest.get('*/customers/:customerId', (req, res, ctx) => {
const {customerId} = req.params
if (customerId === 'customerId') {
return res(
ctx.delay(0),
ctx.status(200),
ctx.json({
authType: 'guest',
customerId: 'customerid'
})
)
}
return res(ctx.delay(0), ctx.status(200), ctx.json(mockedRegisteredCustomer))
})
)
})
afterEach(() => {
jest.resetModules()
localStorage.clear()
})
describe('Logging in tests', function () {
beforeEach(() => {
global.server.use(
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))
})
)
})
test('Shows inline error when email is empty', async () => {
const {user} = renderWithProviders(<MockedComponent />, {
wrapperProps: {
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app,
bypassAuth: false
}
})
// Only fill password, leave email empty
await user.type(screen.getByLabelText('Password'), 'Password!1')
// Try to submit the form
await user.click(screen.getByRole('button', {name: /sign in/i}))
expect(await screen.findByText(/Please enter your email address\./i)).toBeInTheDocument()
})
test('Shows inline error when password is empty', async () => {
const {user} = renderWithProviders(<MockedComponent />, {
wrapperProps: {
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app,
bypassAuth: false
}
})
// Only fill email, leave password empty
await user.type(screen.getByLabelText('Email'), 'customer@test.com')
// Try to submit the form
await user.click(screen.getByRole('button', {name: /sign in/i}))
expect(await screen.findByText(/Please enter your password\./i)).toBeInTheDocument()
})
test('Allows customer to sign in to their account', async () => {
const {user} = renderWithProviders(<MockedComponent />, {
wrapperProps: {
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app,
bypassAuth: false
}
})
// 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.getByRole('button', {name: /sign in/i}))
await waitFor(() => {
expect(window.location.pathname).toBe('/uk/en-GB/account')
expect(screen.getByText(/My Profile/i)).toBeInTheDocument()
})
})
test('allows customer to sign in via Enter key', async () => {
const {user} = renderWithProviders(<MockedComponent />, {
wrapperProps: {
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app,
bypassAuth: false
}
})
// enter credentials
await user.type(screen.getByLabelText('Email'), 'customer@test.com')
await user.type(screen.getByLabelText('Password'), 'Password!1')
// mock successful login response
global.server.use(
rest.post('*/oauth2/token', (req, res, ctx) =>
res(
ctx.delay(0),
ctx.json({
customer_id: 'customerid_1',
access_token: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1hM2M1LTc1NjIzMjY1MmZmNSIsImN0eCI6InNsYXMiLCJpc3MiOiJzbGFzL3Byb2QvenpyZl8wMDEiLCJpc3QiOjEsImF1ZCI6ImNvbW1lcmNlY2xvdWQvcHJvZC96enJmXzAwMSIsIm5iZiI6MTY3ODgzNDI3MSwic3R5IjoiVXNlciIsImlzYiI6InVpZG86ZWNvbTo6dXBuOmtldjVAdGVzdC5jb206OnVpZG46a2V2aW4gaGU6OmdjaWQ6YWJtZXMybWJrM2xYa1JsSEZKd0dZWWt1eEo6OnJjaWQ6YWJVTXNhdnBEOVk2alcwMGRpMlNqeEdDTVU6OmNoaWQ6UmVmQXJjaEdsb2JhbCIsImV4cCI6MjY3ODgzNjEwMSwiaWF0IjoxNjc4ODM0MzAxLCJqdGkiOiJDMkM0ODU2MjAxODYwLTE4OTA2Nzg5MDM0ODA1ODMyNTcwNjY2NTQyIn0._tUrxeXdFYPj6ZoY-GILFRd3-aD1RGPkZX6TqHeS494',
refresh_token: 'testrefeshtoken_1',
usid: 'testusid_1',
enc_user_id: 'testEncUserId_1',
id_token: 'testIdToken_1'
})
)
)
)
// submit via Enter key
await user.keyboard('{Enter}')
await waitFor(() => {
expect(window.location.pathname).toBe('/uk/en-GB/account')
expect(screen.getByText(/My Profile/i)).toBeInTheDocument()
})
})
})
describe('Error while logging in', function () {
beforeEach(() => {
global.server.use(
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))
})
)
})
// 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} = renderWithProviders(<MockedComponent />, {
wrapperProps: {
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app,
bypassAuth: false
}
})
// enter credentials and submit
await user.type(screen.getByLabelText('Email'), 'foo@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))
// wait for login error alert to appear
expect(
await screen.findByText(/Incorrect username or password, please try again./i)
).toBeInTheDocument()
})
})
describe('Navigate away from login page tests', function () {
test('should navigate to sign up page when the user clicks Create Account', async () => {
const {user} = renderWithProviders(<MockedComponent />, {
wrapperProps: {
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app,
isGuest: true
}
})
await user.click(await screen.findByText(/Create Account/i))
await waitFor(async () => {
// wait for sign up page to appear
expect(await screen.findByText(/Let's get started/i)).toBeInTheDocument()
})
})
test('should navigate to reset password page when the user clicks Forgot Password', async () => {
const {user} = renderWithProviders(<MockedComponent />, {
wrapperProps: {
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app,
isGuest: true
}
})
await user.click(screen.getByText(/forgot password/i))
// wait for sign up page to appear
expect(
await screen.findByText(
/Enter your email to receive instructions on how to reset your password/i
)
).toBeInTheDocument()
})
})
describe('Passwordless login tests', () => {
beforeEach(() => {
// Clear the mock before each test
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync.mockClear()
getConfig.mockReturnValue({
app: {
...mockConfig.app,
login: {
passwordless: {
enabled: true,
mode: 'email'
}
}
}
})
})
test('allows passwordless login', async () => {
const {user} = renderWithProviders(<MockedComponent />, {
wrapperProps: {
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app,
bypassAuth: false
}
})
// enter credentials
const testEmail = 'customer@test.com'
await user.type(screen.getByLabelText('Email'), testEmail)
// Click the submit button
await user.click(screen.getByRole('button', {name: /Continue/i}))
// Verify that authorizePasswordless is called with correct parameters
await waitFor(() => {
expect(
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync
).toHaveBeenCalledWith({
userid: testEmail,
mode: 'email'
})
})
// check that check email page is open
await waitFor(
() => {
expect(screen.getByText(/Check Your Email/i)).toBeInTheDocument()
},
{timeout: 5000}
)
// resend the email
await user.click(screen.getByText(/Resend Link/i))
expect(
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync
).toHaveBeenCalledWith({
userid: testEmail,
mode: 'email'
})
})
test.each([
[
"callback_uri doesn't match the registered callbacks",
'This feature is not currently available.'
],
[
'PasswordLess Permissions Error for clientId:aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
'This feature is not currently available.'
],
['client secret is not provided', 'This feature is not currently available.'],
['unexpected error message', 'Something went wrong. Try again!']
])(
'displays correct error message when passwordless login fails with "%s"',
async (apiErrorMessage, expectedMessage) => {
mockAuthHelperFunctions[
AuthHelpers.AuthorizePasswordless
].mutateAsync.mockImplementation(() => {
throw new Error(apiErrorMessage)
})
const {user} = renderWithProviders(<MockedComponent />, {
wrapperProps: {
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app,
bypassAuth: false
}
})
await user.type(screen.getByLabelText('Email'), 'customer@test.com')
await user.click(screen.getByRole('button', {name: /Continue/i}))
expect(screen.getByText(expectedMessage)).toBeInTheDocument()
}
)
})