-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathtest-utils.js
More file actions
256 lines (239 loc) · 10.2 KB
/
test-utils.js
File metadata and controls
256 lines (239 loc) · 10.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
/*
* 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, {useEffect, useRef} from 'react'
import {render} from '@testing-library/react'
import {BrowserRouter as Router} from 'react-router-dom'
import {ChakraProvider} from '@chakra-ui/react'
import PropTypes from 'prop-types'
import theme from '../theme'
import {AddToCartModalProvider} from '../hooks/use-add-to-cart-modal'
import {ServerContext} from '@salesforce/pwa-kit-react-sdk/ssr/universal/contexts'
import {IntlProvider} from 'react-intl'
import {CommerceApiProvider} from '@salesforce/commerce-sdk-react'
import {PageContext, Region} from '@salesforce/commerce-sdk-react/components'
import {withReactQuery} from '@salesforce/pwa-kit-react-sdk/ssr/universal/components/with-react-query'
import fallbackMessages from '../static/translations/compiled/en-GB.json'
import mockConfig from '../../mock-config'
// Contexts
import {CurrencyProvider, MultiSiteProvider} from '../contexts'
import {createUrlTemplate} from './url'
import {getSiteByReference} from './site-utils'
import jwt from 'jsonwebtoken'
import userEvent from '@testing-library/user-event'
// This JWT's payload is special
// it includes 3 fields that commerce-sdk-react cares:
// exp, isb and sub
// The lib decodes the jwt and extract information such as customerId and customerType
const guestPayload = {
aut: 'GUID',
scp: 'sfcc.shopper-myaccount.baskets sfcc.shopper-myaccount.addresses sfcc.shopper-products sfcc.shopper-discovery-search sfcc.shopper-myaccount.rw sfcc.shopper-myaccount.paymentinstruments sfcc.shopper-customers.login sfcc.shopper-experience sfcc.shopper-context.rw sfcc.shopper-myaccount.orders sfcc.shopper-customers.register sfcc.shopper-baskets-orders sfcc.shopper-myaccount.addresses.rw sfcc.shopper-myaccount.productlists.rw sfcc.shopper-productlists sfcc.shopper-promotions sfcc.shopper-baskets-orders.rw sfcc.shopper-myaccount.paymentinstruments.rw sfcc.shopper-gift-certificates sfcc.shopper-product-search sfcc.shopper-myaccount.productlists sfcc.shopper-categories sfcc.shopper-myaccount',
sub: 'cc-slas::zzrf_001::scid:c9c45bfd-0ed3-4aa2-9971-40f88962b836::usid:02ccab32-d01e-4abc-809a-a457fa0512c2',
ctx: 'slas',
iss: 'slas/prod/zzrf_001',
ist: 1,
aud: 'commercecloud/prod/zzrf_001',
nbf: 1679013708,
sty: 'User',
isb: 'uido:slas::upn:Guest::uidn:Guest User::gcid:bckbhHw0dGkXgRxbaVxqYYwuhH::chid: ',
exp: 1924905600000,
iat: 1679013738,
jti: 'C2C4856201860-18906789034985270413965222'
}
const registeredUserPayload = {
aut: 'GUID',
scp: 'sfcc.shopper-myaccount.baskets sfcc.shopper-myaccount.addresses sfcc.shopper-products sfcc.shopper-discovery-search sfcc.shopper-myaccount.rw sfcc.shopper-myaccount.paymentinstruments sfcc.shopper-customers.login sfcc.shopper-experience sfcc.shopper-myaccount.orders sfcc.shopper-customers.register sfcc.shopper-baskets-orders sfcc.shopper-myaccount.addresses.rw sfcc.shopper-myaccount.productlists.rw sfcc.shopper-productlists sfcc.shopper-promotions sfcc.shopper-baskets-orders.rw sfcc.shopper-myaccount.paymentinstruments.rw sfcc.shopper-gift-certificates sfcc.shopper-product-search sfcc.shopper-myaccount.productlists sfcc.shopper-categories sfcc.shopper-myaccount',
sub: 'cc-slas::zzrf_001::scid:c9c45bfd-0ed3-4aa2-9971-40f88962b836::usid:8e883973-68eb-41fe-a3c5-756232652ff5',
ctx: 'slas',
iss: 'slas/prod/zzrf_001',
ist: 1,
aud: 'commercecloud/prod/zzrf_001',
nbf: 1678834271,
sty: 'User',
isb: 'uido:ecom::upn:kev5@test.com::uidn:kevin he::gcid:abmes2mbk3lXkRlHFJwGYYkuxJ::rcid:abUMsavpD9Y6jW00di2SjxGCMU::chid:RefArchGlobal',
exp: 2678836101,
iat: 1678834301,
jti: 'C2C4856201860-18906789034805832570666542'
}
export const guestToken = jwt.sign(guestPayload, 'secret')
export const registerUserToken = jwt.sign(registeredUserPayload, 'secret')
export const DEFAULT_LOCALE = 'en-GB'
export const DEFAULT_CURRENCY = 'GBP'
export const SUPPORTED_LOCALES = [
{
id: 'en-GB',
preferredCurrency: 'GBP'
},
{
id: 'de-DE',
preferredCurrency: 'EUR'
}
]
export const DEFAULT_SITE = 'global'
export const renderWithReactIntl = (node, locale = DEFAULT_LOCALE) => {
return render(
<IntlProvider locale={locale} defaultLocale={locale}>
{node}
</IntlProvider>
)
}
export const renderWithRouter = (node) => renderWithReactIntl(<Router>{node}</Router>)
/**
* This is the Providers used to wrap components
* for testing purposes.
* @param {object} props
*/
export const TestProviders = ({
children,
locale = {id: DEFAULT_LOCALE},
messages = fallbackMessages,
config = mockConfig,
site,
siteAlias = DEFAULT_SITE,
isGuest = false,
bypassAuth = true
}) => {
const mounted = useRef()
// We use this to track mounted state.
useEffect(() => {
mounted.current = true
return () => {
mounted.current = false
}
}, [])
// Prioritize the site prop over the siteAlias prop or the default site
site = site || getSiteByReference(siteAlias || config.defaultSite)
const commerceApiConfig = config.commerceAPI
const buildUrl = createUrlTemplate(config, site?.alias || site?.id, locale.alias || locale.id)
return (
<ServerContext.Provider value={{}}>
<IntlProvider locale={locale.id} defaultLocale={DEFAULT_LOCALE} messages={messages}>
<MultiSiteProvider site={site} locale={locale} buildUrl={buildUrl}>
<CommerceApiProvider
shortCode={commerceApiConfig.parameters.shortCode}
clientId={commerceApiConfig.parameters.clientId}
organizationId={commerceApiConfig.parameters.organizationId}
siteId={site?.id}
locale={locale.id}
proxy={`${window.location.origin}/${commerceApiConfig.proxyPath}`}
redirectURI={`${window.location.origin}/testcallback`}
fetchedToken={bypassAuth ? (isGuest ? guestToken : registerUserToken) : ''}
>
<CurrencyProvider currency={DEFAULT_CURRENCY}>
<Router>
<ChakraProvider theme={theme}>
<AddToCartModalProvider>{children}</AddToCartModalProvider>
</ChakraProvider>
</Router>
</CurrencyProvider>
</CommerceApiProvider>
</MultiSiteProvider>
</IntlProvider>
</ServerContext.Provider>
)
}
TestProviders.propTypes = {
children: PropTypes.element,
initialBasket: PropTypes.object,
initialCustomer: PropTypes.object,
initialProductLists: PropTypes.object,
messages: PropTypes.object,
locale: PropTypes.object,
config: PropTypes.object,
site: PropTypes.object,
siteAlias: PropTypes.string,
bypassAuth: PropTypes.bool,
isGuest: PropTypes.bool
}
/**
* This is used to wrap components for testing
* purposes. You will need to wrap the components
* which need access to certain contexts, such as
* the theme, router and internationlization, etc.
* @param {object} children
* @param {object} options
*/
export const renderWithProviders = (children, options) => {
const TestProvidersWithDataAPI = withReactQuery(TestProviders, {
queryClientConfig: {
defaultOptions: {
queries: {
retry: false,
staleTime: 2 * 1000
},
mutations: {
retry: false
}
}
}
})
const user = userEvent.setup()
const locals = {}
const res = render(children, {
wrapper: () => (
<TestProvidersWithDataAPI {...options?.wrapperProps} locals={locals}>
{children}
</TestProvidersWithDataAPI>
),
...options
})
return {user, ...res}
}
/**
* This is used to construct the URL pathname that would include
* or not include the default locale and site identifiers in the URL according to
* their configuration set in config/mocks/default.js file.
*
* @param path The pathname that we want to use
* @returns {string} URL pathname for the given path
*/
export const createPathWithDefaults = (path) => {
const {siteAliases, sites} = mockConfig
const defaultSite = sites.find((site) => site.id === mockConfig.defaultSite)
const siteAlias = siteAliases[defaultSite.id]
const defaultLocale = defaultSite.l10n.defaultLocale
const buildUrl = createUrlTemplate(mockConfig, siteAlias || defaultSite, defaultLocale)
const updatedPath = buildUrl(path, siteAlias || defaultSite.id, defaultLocale)
return updatedPath
}
/**
* When testing page designer components wrap them using this higher-order component
* if you plan on using `Region` of `Components` within the components definition.
*
* @param {*} Component
* @param {*} options
* @returns
*/
export const withPageProvider = (Component, options) => {
const providerProps = options?.providerProps || {
value: {
components: new Proxy(
{},
{
// eslint-disable-next-line @typescript-eslint/no-unused-vars
get(_target, _prop) {
return (props) => (
<div>
<b>{props.typeId}</b>
{props?.regions?.map((region) => (
<Region key={region.id} region={region} />
))}
</div>
)
}
}
)
}
}
const wrappedComponentName = Component.displayName || Component.name
const WrappedComponent = (props) => (
<PageContext.Provider {...providerProps}>
<Component {...props} />
</PageContext.Provider>
)
WrappedComponent.displayName = `withRouter(${wrappedComponentName})`
return WrappedComponent
}