-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathindex.test.js
More file actions
622 lines (537 loc) · 24.2 KB
/
index.test.js
File metadata and controls
622 lines (537 loc) · 24.2 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
/*
* 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 Checkout from '@salesforce/retail-react-app/app/pages/checkout/index'
import {Route, Switch} from 'react-router-dom'
import {screen, waitFor, within} from '@testing-library/react'
import {rest} from 'msw'
import {
renderWithProviders,
createPathWithDefaults
} from '@salesforce/retail-react-app/app/utils/test-utils'
import {
scapiBasketWithItem,
mockShippingMethods,
mockedRegisteredCustomer,
mockedCustomerProductLists
} from '@salesforce/retail-react-app/app/mocks/mock-data'
import mockConfig from '@salesforce/retail-react-app/config/mocks/default'
// This is a flaky test file!
jest.retryTimes(5)
jest.setTimeout(40_000)
// Minimal subset of `ocapiOrderResponse` in app/mocks/mock-data.js
const scapiOrderResponse = {
orderNo: '00000101',
customerInfo: {
customerId: 'customerid',
customerNo: 'jlebowski',
email: 'jeff@lebowski.com'
}
}
const defaultShippingMethod = mockShippingMethods.applicableShippingMethods.find(
(method) => method.id === mockShippingMethods.defaultShippingMethodId
)
// This is our wrapped component for testing. It handles initialization of the customer
// and basket the same way it would be when rendered in the real app. We also set up
// fake routes to simulate moving from checkout to confirmation page.
const WrappedCheckout = () => {
return (
<Switch>
<Route exact path={createPathWithDefaults('/checkout')}>
<Checkout />
</Route>
<Route
exact
path={createPathWithDefaults(
`/checkout/confirmation/${scapiOrderResponse.orderNo}`
)}
>
<div>success</div>
</Route>
</Switch>
)
}
// Set up and clean up
beforeEach(() => {
global.server.use(
// mock product details
rest.get('*/products', (req, res, ctx) => {
return res(
ctx.json({
data: [
{
id: '701643070725M',
currency: 'GBP',
name: 'Long Sleeve Crew Neck',
pricePerUnit: 19.18,
price: 19.18,
inventory: {
stockLevel: 10,
orderable: true,
backorder: false,
preorderable: false
}
}
]
})
)
}),
// mock the available shipping methods
rest.get('*/shipments/me/shipping-methods', (req, res, ctx) => {
return res(ctx.delay(0), ctx.json(mockShippingMethods))
})
)
let currentBasket = JSON.parse(JSON.stringify(scapiBasketWithItem))
// Set up additional requests for intercepting/mocking for just this test.
global.server.use(
// mock adding guest email to basket
rest.put('*/baskets/:basketId/customer', (req, res, ctx) => {
currentBasket.customerInfo.email = 'customer@test.com'
return res(ctx.json(currentBasket))
}),
// mock fetch product lists
rest.get('*/customers/:customerId/product-lists', (req, res, ctx) => {
return res(ctx.json(mockedCustomerProductLists))
}),
// mock add shipping and billing address to basket
rest.put('*/shipping-address', (req, res, ctx) => {
const shippingBillingAddress = {
address1: req.body.address1,
city: 'Tampa',
countryCode: 'US',
firstName: 'Test',
fullName: 'Test McTester',
id: '047b18d4aaaf4138f693a4b931',
lastName: 'McTester',
phone: '(727) 555-1234',
postalCode: '33712',
stateCode: 'FL'
}
currentBasket.shipments[0].shippingAddress = shippingBillingAddress
currentBasket.billingAddress = shippingBillingAddress
return res(ctx.json(currentBasket))
}),
// mock add billing address to basket
rest.put('*/billing-address', (req, res, ctx) => {
const shippingBillingAddress = {
address1: '123 Main St',
city: 'Tampa',
countryCode: 'US',
firstName: 'John',
fullName: 'John Smith',
id: '047b18d4aaaf4138f693a4b931',
lastName: 'Smith',
phone: '(727) 555-1234',
postalCode: '33712',
stateCode: 'FL',
_type: 'orderAddress'
}
currentBasket.shipments[0].shippingAddress = shippingBillingAddress
currentBasket.billingAddress = shippingBillingAddress
return res(ctx.json(currentBasket))
}),
// mock add shipping method
rest.put('*/shipments/me/shipping-method', (req, res, ctx) => {
currentBasket.shipments[0].shippingMethod = defaultShippingMethod
return res(ctx.json(currentBasket))
}),
// mock add payment instrument
rest.post('*/baskets/:basketId/payment-instruments', (req, res, ctx) => {
currentBasket.paymentInstruments = [
{
amount: 0,
paymentCard: {
cardType: 'Master Card',
creditCardExpired: false,
expirationMonth: 1,
expirationYear: 2040,
holder: 'Test McTester',
maskedNumber: '************5454',
numberLastDigits: '5454',
validFromMonth: 1,
validFromYear: 2020
},
paymentInstrumentId: 'testcard1',
paymentMethodId: 'CREDIT_CARD'
}
]
return res(ctx.json(currentBasket))
}),
// mock update address
rest.patch('*/addresses/savedaddress1', (req, res, ctx) => {
return res(ctx.json(mockedRegisteredCustomer.addresses[0]))
}),
// mock place order
rest.post('*/orders', (req, res, ctx) => {
const response = {
...currentBasket,
...scapiOrderResponse,
customerInfo: {...scapiOrderResponse.customerInfo, email: 'customer@test.com'},
status: 'created'
}
return res(ctx.json(response))
}),
rest.get('*/baskets', (req, res, ctx) => {
const baskets = {
baskets: [currentBasket],
total: 1
}
return res(ctx.json(baskets))
})
)
})
afterEach(() => {
jest.resetModules()
localStorage.clear()
})
test('Renders skeleton until customer and basket are loaded', () => {
const {getByTestId, queryByTestId} = renderWithProviders(<Checkout />)
expect(getByTestId('sf-checkout-skeleton')).toBeInTheDocument()
expect(queryByTestId('sf-checkout-container')).not.toBeInTheDocument()
})
test('Can proceed through checkout steps as guest', async () => {
// Keep a *deep* copy of the initial mocked basket. Our mocked fetch responses will continuously
// update this object, which essentially mimics a saved basket on the backend.
let currentBasket = JSON.parse(JSON.stringify(scapiBasketWithItem))
// Set up additional requests for intercepting/mocking for just this test.
global.server.use(
// mock adding guest email to basket
rest.put('*/baskets/:basketId/customer', (req, res, ctx) => {
currentBasket.customerInfo.email = 'test@test.com'
return res(ctx.json(currentBasket))
}),
// mock add shipping and billing address to basket
rest.put('*/shipping-address', (req, res, ctx) => {
const shippingBillingAddress = {
address1: '123 Main St',
city: 'Tampa',
countryCode: 'US',
firstName: 'Tester',
fullName: 'Tester McTesting',
id: '047b18d4aaaf4138f693a4b931',
lastName: 'McTesting',
phone: '(727) 555-1234',
postalCode: '33610',
stateCode: 'FL'
}
currentBasket.shipments[0].shippingAddress = shippingBillingAddress
currentBasket.billingAddress = shippingBillingAddress
return res(ctx.json(currentBasket))
}),
// mock add billing address to basket
rest.put('*/billing-address', (req, res, ctx) => {
const shippingBillingAddress = {
address1: '123 Main St',
city: 'Tampa',
countryCode: 'US',
firstName: 'Tester',
fullName: 'Tester McTesting',
id: '047b18d4aaaf4138f693a4b931',
lastName: 'McTesting',
phone: '(727) 555-1234',
postalCode: '33610',
stateCode: 'FL'
}
currentBasket.shipments[0].shippingAddress = shippingBillingAddress
currentBasket.billingAddress = shippingBillingAddress
return res(ctx.json(currentBasket))
}),
// mock add shipping method
rest.put('*/shipments/me/shipping-method', (req, res, ctx) => {
currentBasket.shipments[0].shippingMethod = defaultShippingMethod
return res(ctx.json(currentBasket))
}),
// mock add payment instrument
rest.post('*/baskets/:basketId/payment-instruments', (req, res, ctx) => {
currentBasket.paymentInstruments = [
{
amount: 0,
paymentCard: {
cardType: 'Visa',
creditCardExpired: false,
expirationMonth: 1,
expirationYear: 2040,
holder: 'Testy McTester',
maskedNumber: '************1111',
numberLastDigits: '1111',
validFromMonth: 1,
validFromYear: 2020
},
paymentInstrumentId: '875cae2724408c9a3eb45715ba',
paymentMethodId: 'CREDIT_CARD'
}
]
return res(ctx.json(currentBasket))
}),
// mock place order
rest.post('*/orders', (req, res, ctx) => {
const response = {
...currentBasket,
...scapiOrderResponse,
customerInfo: {...scapiOrderResponse.customerInfo, email: 'customer@test.com'},
status: 'created'
}
return res(ctx.json(response))
}),
rest.get('*/baskets', (req, res, ctx) => {
const baskets = {
baskets: [currentBasket],
total: 1
}
return res(ctx.json(baskets))
})
)
// Set the initial browser router path and render our component tree.
window.history.pushState({}, 'Checkout', createPathWithDefaults('/checkout'))
const {user} = renderWithProviders(<WrappedCheckout history={history} />, {
wrapperProps: {isGuest: true, siteAlias: 'uk', appConfig: mockConfig.app}
})
// Wait for checkout to load and display first step
await screen.findByText(/checkout as guest/i)
// Verify cart products display
await user.click(screen.getByText(/2 items in cart/i))
expect(await screen.findByText(/Long Sleeve Crew Neck$/i)).toBeInTheDocument()
// Verify password field is reset if customer toggles login form
const loginToggleButton = screen.getByText(/Already have an account\? Log in/i)
await user.click(loginToggleButton)
// Provide customer email and submit
const passwordInput = document.querySelector('input[type="password"]')
await user.type(passwordInput, 'Password1!')
const checkoutAsGuestButton = screen.getByText(/Checkout as guest/i)
await user.click(checkoutAsGuestButton)
// Provide customer email and submit
const emailInput = screen.getByLabelText(/email/i)
const submitBtn = screen.getByText(/checkout as guest/i)
await user.type(emailInput, 'test@test.com')
await user.click(submitBtn)
// Wait for next step to render
await waitFor(() => {
expect(screen.getByTestId('sf-toggle-card-step-1-content')).not.toBeEmptyDOMElement()
})
// Email should be displayed in previous step summary
expect(screen.getByText('test@test.com')).toBeInTheDocument()
// Shipping Address Form must be present
expect(screen.getByLabelText('Shipping Address Form')).toBeInTheDocument()
// Fill out shipping address form and submit
await user.type(screen.getByLabelText(/first name/i), 'Tester')
await user.type(screen.getByLabelText(/last name/i), 'McTesting')
await user.type(screen.getByLabelText(/phone/i), '(727) 555-1234')
await user.type(screen.getAllByLabelText(/address/i)[0], '123 Main St')
await user.type(screen.getByLabelText(/city/i), 'Tampa')
await user.selectOptions(screen.getByLabelText(/state/i), ['FL'])
await user.type(screen.getByLabelText(/zip code/i), '33610')
await user.click(screen.getByText(/continue to shipping method/i))
// Wait for next step to render
await waitFor(() => {
expect(screen.getByTestId('sf-toggle-card-step-2-content')).not.toBeEmptyDOMElement()
})
// Shipping address displayed in previous step summary
expect(screen.getByText('Tester McTesting')).toBeInTheDocument()
expect(screen.getByText('123 Main St')).toBeInTheDocument()
expect(screen.getByText('Tampa, FL 33610')).toBeInTheDocument()
expect(screen.getByText('US')).toBeInTheDocument()
// Default shipping option should be selected
const shippingOptionsForm = screen.getByTestId('sf-checkout-shipping-options-form')
await waitFor(() =>
expect(shippingOptionsForm).toHaveFormValues({
'shipping-options-radiogroup': mockShippingMethods.defaultShippingMethodId
})
)
// Submit selected shipping method
await user.click(screen.getByText(/continue to payment/i))
// Wait for next step to render
await waitFor(() => {
expect(screen.getByTestId('sf-toggle-card-step-3-content')).not.toBeEmptyDOMElement()
})
// Applied shipping method should be displayed in previous step summary
expect(screen.getByText(defaultShippingMethod.name)).toBeInTheDocument()
// Fill out credit card payment form
await user.type(screen.getByLabelText(/card number/i), '4111111111111111')
await user.type(screen.getByLabelText(/name on card/i), 'Testy McTester')
await user.type(screen.getByLabelText(/expiration date/i), '0140')
await user.type(screen.getByLabelText(/^security code$/i /* not "security code info" */), '123')
// Same as shipping checkbox selected by default
expect(screen.getByLabelText(/same as shipping address/i)).toBeChecked()
// Should display billing address that matches shipping address
const step3Content = within(screen.getByTestId('sf-toggle-card-step-3-content'))
expect(step3Content.getByText('Tester McTesting')).toBeInTheDocument()
expect(step3Content.getByText('123 Main St')).toBeInTheDocument()
expect(step3Content.getByText('Tampa, FL 33610')).toBeInTheDocument()
expect(step3Content.getByText('US')).toBeInTheDocument()
// Move to final review step
await user.click(screen.getByText(/review order/i))
const placeOrderBtn = await screen.findByTestId('sf-checkout-place-order-btn', undefined, {
timeout: 5000
})
// Verify applied payment and billing address
expect(step3Content.getByText('Visa')).toBeInTheDocument()
expect(step3Content.getByText('•••• 1111')).toBeInTheDocument()
expect(step3Content.getByText('1/2040')).toBeInTheDocument()
expect(step3Content.getByText('Tester McTesting')).toBeInTheDocument()
expect(step3Content.getByText('123 Main St')).toBeInTheDocument()
expect(step3Content.getByText('Tampa, FL 33610')).toBeInTheDocument()
expect(step3Content.getByText('US')).toBeInTheDocument()
// Place the order
await user.click(placeOrderBtn)
// Should now be on our mocked confirmation route/page
expect(await screen.findByText(/success/i)).toBeInTheDocument()
})
test('Can proceed through checkout as registered customer', async () => {
// Set the initial browser router path and render our component tree.
window.history.pushState({}, 'Checkout', createPathWithDefaults('/checkout'))
const {user} = renderWithProviders(<WrappedCheckout history={history} />, {
wrapperProps: {
// Not bypassing auth as usual, so we can test the guest-to-registered flow
bypassAuth: true,
isGuest: false,
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app
}
})
// Email should be displayed in previous step summary
await waitFor(() => {
expect(screen.getByText('customer@test.com')).toBeInTheDocument()
})
// Select a saved address and continue
await user.click(screen.getByDisplayValue('savedaddress1'))
await user.click(screen.getByText(/continue to shipping method/i))
// Wait for next step to render
await waitFor(() => {
expect(screen.getByTestId('sf-toggle-card-step-2-content')).not.toBeEmptyDOMElement()
})
// Shipping address displayed in previous step summary
expect(screen.getByText('Test McTester')).toBeInTheDocument()
expect(screen.getByText('123 Main St')).toBeInTheDocument()
// Default shipping option should be selected
const shippingOptionsForm = screen.getByTestId('sf-checkout-shipping-options-form')
await waitFor(() =>
expect(shippingOptionsForm).toHaveFormValues({
'shipping-options-radiogroup': mockShippingMethods.defaultShippingMethodId
})
)
// Submit selected shipping method
await user.click(screen.getByText(/continue to payment/i))
// Wait for next step to render
await waitFor(() => {
expect(screen.getByTestId('sf-toggle-card-step-3-content')).not.toBeEmptyDOMElement()
})
// Applied shipping method should be displayed in previous step summary
expect(screen.getByText(defaultShippingMethod.name)).toBeInTheDocument()
// Fill out credit card payment form
// (we no longer have saved payment methods)
await user.type(screen.getByLabelText(/card number/i), '4111111111111111')
await user.type(screen.getByLabelText(/name on card/i), 'Testy McTester')
await user.type(screen.getByLabelText(/expiration date/i), '0140')
await user.type(screen.getByLabelText(/^security code$/i /* not "security code info" */), '123')
// Same as shipping checkbox selected by default
expect(screen.getByLabelText(/same as shipping address/i)).toBeChecked()
// Should display billing address that matches shipping address
const step3Content = within(screen.getByTestId('sf-toggle-card-step-3-content'))
expect(step3Content.getByText('123 Main St')).toBeInTheDocument()
// Edit billing address
const sameAsShippingBtn = screen.getByText(/same as shipping address/i)
await user.click(sameAsShippingBtn)
const firstNameInput = screen.getByLabelText(/first name/i)
const lastNameInput = screen.getByLabelText(/last name/i)
expect(step3Content.queryByText(/Set as default/)).not.toBeInTheDocument()
await user.clear(firstNameInput)
await user.clear(lastNameInput)
await user.type(firstNameInput, 'John')
await user.type(lastNameInput, 'Smith')
// Move to final review step
await user.click(screen.getByText(/review order/i))
const placeOrderBtn = await screen.findByTestId('sf-checkout-place-order-btn', undefined, {
timeout: 5000
})
// Verify applied payment and billing address
expect(step3Content.getByText('Master Card')).toBeInTheDocument()
expect(step3Content.getByText('•••• 5454')).toBeInTheDocument()
expect(step3Content.getByText('1/2040')).toBeInTheDocument()
expect(step3Content.getByText('John Smith')).toBeInTheDocument()
expect(step3Content.getByText('123 Main St')).toBeInTheDocument()
// Place the order
await user.click(placeOrderBtn)
// Should now be on our mocked confirmation route/page
expect(await screen.findByText(/success/i)).toBeInTheDocument()
document.cookie = ''
})
test('Can edit address during checkout as a registered customer', async () => {
// Set the initial browser router path and render our component tree.
window.history.pushState({}, 'Checkout', createPathWithDefaults('/checkout'))
const {user} = renderWithProviders(<WrappedCheckout history={history} />, {
wrapperProps: {
// Not bypassing auth as usual, so we can test the guest-to-registered flow
bypassAuth: true,
isGuest: false,
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app
}
})
await waitFor(() => {
expect(screen.getByTestId('sf-checkout-shipping-address-0')).toBeInTheDocument()
})
const firstAddress = screen.getByTestId('sf-checkout-shipping-address-0')
await user.click(within(firstAddress).getByText(/edit/i))
// Wait for the edit address form to render
await waitFor(() =>
expect(screen.getByTestId('sf-shipping-address-edit-form')).not.toBeEmptyDOMElement()
)
// Shipping Address Form must be present
expect(screen.getByLabelText('Shipping Address Form')).toBeInTheDocument()
expect(screen.getByLabelText(/first name/i)).toBeInTheDocument()
// Edit and save the address
await user.clear(screen.getByLabelText('Address'))
await user.type(screen.getByLabelText('Address'), '369 Main Street')
await user.click(screen.getByText(/save & continue to shipping method/i))
// Wait for next step to render
await waitFor(() => {
expect(screen.getByTestId('sf-toggle-card-step-2-content')).not.toBeEmptyDOMElement()
})
expect(screen.getByText('369 Main Street')).toBeInTheDocument()
})
test('Can add address during checkout as a registered customer', async () => {
// Set the initial browser router path and render our component tree.
window.history.pushState({}, 'Checkout', createPathWithDefaults('/checkout'))
const {user} = renderWithProviders(<WrappedCheckout history={history} />, {
wrapperProps: {
// Not bypassing auth as usual, so we can test the guest-to-registered flow
bypassAuth: true,
isGuest: false,
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app
}
})
global.server.use(
rest.post('*/customers/:customerId/addresses', (req, res, ctx) => {
return res(ctx.delay(0), ctx.status(200), ctx.json(req.body))
})
)
await waitFor(() => {
expect(screen.getByText(/add new address/i)).toBeInTheDocument()
})
// Add address
await user.click(screen.getByText(/add new address/i))
// Shipping Address Form must be present
expect(screen.getByLabelText('Shipping Address Form')).toBeInTheDocument()
const firstName = await screen.findByLabelText(/first name/i)
await user.type(firstName, 'Test2')
await user.type(screen.getByLabelText(/last name/i), 'McTester')
await user.type(screen.getByLabelText(/phone/i), '7275551234')
await user.selectOptions(screen.getByLabelText(/country/i), ['US'])
await user.type(screen.getAllByLabelText(/address/i)[0], 'Tropicana Field')
await user.type(screen.getByLabelText(/city/i), 'Tampa')
await user.selectOptions(screen.getByLabelText(/state/i), ['FL'])
await user.type(screen.getByLabelText(/zip code/i), '33712')
await user.click(screen.getByText(/save & continue to shipping method/i))
// Wait for next step to render
await waitFor(() => {
expect(screen.getByTestId('sf-toggle-card-step-2-content')).not.toBeEmptyDOMElement()
})
})