-
Notifications
You must be signed in to change notification settings - Fork 214
Expand file tree
/
Copy pathseo-hoc.test.tsx
More file actions
322 lines (291 loc) · 12.1 KB
/
seo-hoc.test.tsx
File metadata and controls
322 lines (291 loc) · 12.1 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
/*
* 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 {render, screen, waitFor, act} from '@testing-library/react'
import {BrowserRouter, useLocation} from 'react-router-dom'
import SeoHOC from './seo-hoc'
import {useExtensionConfig} from '../hooks/use-extension-config'
// Mock the useLocation hook
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useLocation: jest.fn()
}))
// Mock the useExtensionConfig hook
jest.mock('../hooks/use-extension-config', () => ({
useExtensionConfig: jest.fn()
}))
// Mock useRoutes and useBlockNavigation
let mockSetIsNavigationBlocked: jest.Mock
jest.mock('@salesforce/pwa-kit-extension-sdk/react', () => {
mockSetIsNavigationBlocked = jest.fn()
return {
useApplicationExtensionsStore: jest.fn().mockImplementation((selector) => {
const state = {
state: {
'@salesforce/extension-commerce-bm-seo': {
setIsNavigationBlocked: mockSetIsNavigationBlocked,
siteLocale: 'en-US'
}
}
}
return selector(state)
})
}
})
// Mock the useUrlMapping hook
let mockRefetch: jest.Mock
jest.mock('@salesforce/commerce-sdk-react', () => {
mockRefetch = jest.fn().mockResolvedValue({
status: 'success',
data: {destinationUrl: '/redirect'}
})
return {
useUrlMapping: jest.fn().mockReturnValue({
refetch: mockRefetch
})
}
})
// Mock useRoutes and useBlockNavigation
let navCallback: ((location: any, action: string) => Promise<void>) | undefined
jest.mock('@salesforce/pwa-kit-react-sdk/ssr/universal/hooks', () => {
const originalModule = jest.requireActual('@salesforce/pwa-kit-react-sdk/ssr/universal/hooks')
return {
...originalModule,
useRoutes: jest.fn(),
useBlockNavigation: jest.fn().mockImplementation((cb) => {
const isBlocked = true
navCallback = cb
return {isBlocked, blockNavigation: jest.fn(), unblockNavigation: jest.fn()}
})
}
})
let setRoutesMock: jest.Mock
const setupForSetRoutesTests = ({pathname}: {pathname: string}) => {
const ProductDetail = () => <div>Test Component</div>
const insideComponent = () => <div>Inner Component</div>
ProductDetail.displayName = 'ProductDetail'
;(useExtensionConfig as jest.Mock).mockReturnValue({
routingMode: 'router_first',
resourceTypeToComponentMap: {
category: 'ProductList',
product: 'ProductDetail',
content_asset: 'ProductList'
}
})
;(useLocation as jest.Mock).mockReturnValue({
pathname: pathname
})
// Mock useRoutes to return predefined routes
const mockRoutes = [
{path: '/products/:id', component: ProductDetail},
{path: '/category/:id', component: ProductDetail},
{path: '/some-path', component: ProductDetail},
{path: '*', component: ProductDetail}
]
setRoutesMock = jest.fn()
;(
jest.requireMock('@salesforce/pwa-kit-react-sdk/ssr/universal/hooks').useRoutes as jest.Mock
).mockReturnValue({
routes: mockRoutes,
setRoutes: setRoutesMock
})
const WrappedComponent = SeoHOC(insideComponent)
return {WrappedComponent}
}
describe('SeoHOC', () => {
beforeEach(() => {
// Reset all mocks before each test
jest.clearAllMocks()
// Default mock for useLocation
;(useLocation as jest.Mock).mockReturnValue({
pathname: '/products/123'
})
})
describe('router_first strategy', () => {
afterAll(() => {
;(
jest.requireMock('@salesforce/commerce-sdk-react').useUrlMapping as jest.Mock
).mockImplementation(() => ({
refetch: mockRefetch
}))
})
it('should skip URL mapping when route is defined and strategy is router_first', () => {
const MockComponent = () => <div>Test Component</div>
const WrappedComponent = SeoHOC(MockComponent)
// Mock useExtensionConfig to return router_first strategy
;(useExtensionConfig as jest.Mock).mockReturnValue({
routingMode: 'router_first',
resourceTypeToComponentMap: {}
})
// Mock useRoutes to return predefined routes
const mockRoutes = [
{path: '/products/:id', component: MockComponent},
{path: '/category/:id', component: MockComponent},
{path: '*', component: MockComponent} // Catch-all route
]
;(
jest.requireMock('@salesforce/pwa-kit-react-sdk/ssr/universal/hooks')
.useRoutes as jest.Mock
).mockReturnValue({
routes: mockRoutes,
setRoutes: jest.fn()
})
// Mock useUrlMapping to ensure it's not called
const mockRefetch = jest.fn()
;(
jest.requireMock('@salesforce/commerce-sdk-react').useUrlMapping as jest.Mock
).mockReturnValue({
refetch: mockRefetch
})
render(
<BrowserRouter>
<WrappedComponent />
</BrowserRouter>
)
// Verify that the component renders without calling URL mapping
expect(screen.getByText('Test Component')).toBeInTheDocument()
expect(mockRefetch).not.toHaveBeenCalled()
})
it('should proceed with URL mapping when route is not defined and strategy is router_first', () => {
const MockComponent = () => <div>Test Component</div>
const WrappedComponent = SeoHOC(MockComponent)
// Mock useExtensionConfig to return router_first strategy
;(useExtensionConfig as jest.Mock).mockReturnValue({
routingMode: 'router_first',
resourceTypeToComponentMap: {}
})
// Mock useRoutes to return only catch-all route
const mockRoutes = [{path: '*', component: MockComponent}]
;(
jest.requireMock('@salesforce/pwa-kit-react-sdk/ssr/universal/hooks')
.useRoutes as jest.Mock
).mockReturnValue({
routes: mockRoutes,
setRoutes: jest.fn()
})
// Mock useUrlMapping to ensure it's called
const mockRefetch = jest.fn()
;(
jest.requireMock('@salesforce/commerce-sdk-react').useUrlMapping as jest.Mock
).mockReturnValue({
refetch: mockRefetch
})
render(
<BrowserRouter>
<WrappedComponent />
</BrowserRouter>
)
// Verify that URL mapping is called when route is not defined
expect(mockRefetch).toHaveBeenCalled()
})
})
describe('setRoutes and isNavigationBlocked call', () => {
it('renders the wrapped component and passes props', () => {
const {WrappedComponent} = setupForSetRoutesTests({pathname: '/another-path'})
render(<WrappedComponent />)
// expect the component to render
expect(screen.getByText('Inner Component')).toBeInTheDocument()
})
it('calls setIsNavigationBlocked when isBlocked changes', () => {
const {WrappedComponent} = setupForSetRoutesTests({pathname: '/another-path'})
render(<WrappedComponent />)
expect(mockSetIsNavigationBlocked).toHaveBeenCalledWith(true)
})
it('calls setRoutes with Redirect component if resourceType is undefined', async () => {
// Set the mockRefetch response for this test BEFORE setupForSetRoutesTests
mockRefetch.mockResolvedValue({
status: 'success',
data: {destinationUrl: '/redirect'}
})
const {WrappedComponent} = setupForSetRoutesTests({pathname: '/another-path'})
render(<WrappedComponent />)
await act(async () => {
await navCallback?.({pathname: '/some-path'}, 'PUSH')
})
await waitFor(() => {
expect(setRoutesMock).toHaveBeenCalled()
})
const call = setRoutesMock.mock.calls[0][0][0]
expect(call.path).toBe('/some-path')
expect(call.component().type.displayName || call.component().type.name).toMatch(
/Redirect/
)
})
it('calls setRoutes with custom component if urlMappingResponse has resourceType', async () => {
// Set the mockRefetch response for this test
mockRefetch.mockResolvedValue({
status: 'success',
data: {destinationUrl: '/redirect', resourceType: 'product'}
})
const {WrappedComponent} = setupForSetRoutesTests({pathname: '/another-path'})
render(<WrappedComponent />)
await act(async () => {
await navCallback?.({pathname: '/some-path'}, 'PUSH')
})
await waitFor(() => {
expect(setRoutesMock).toHaveBeenCalled()
})
const call = setRoutesMock.mock.calls[0][0][0]
expect(call.path).toBe('/some-path')
// The component should be a function that renders a Redirect
expect(call.component().type.displayName).toBe('ProductDetail')
})
it('handles refetch error status gracefully', async () => {
const {WrappedComponent} = setupForSetRoutesTests({pathname: '/another-path'})
mockRefetch.mockResolvedValueOnce({
status: 'error',
data: undefined
})
render(<WrappedComponent />)
await act(async () => {
await navCallback?.({pathname: '/error-path'}, 'PUSH')
})
// Should not throw, and setRoutes should not be called
expect(setRoutesMock).not.toHaveBeenCalled()
})
it('handles error status from refetch', async () => {
const {WrappedComponent} = setupForSetRoutesTests({pathname: '/another-path'})
mockRefetch.mockResolvedValueOnce({
status: 'error',
data: undefined
})
render(<WrappedComponent />)
await act(async () => {
await navCallback?.({pathname: '/no-data-path'}, 'PUSH')
})
// Should not throw, and setRoutes should not be called
expect(setRoutesMock).not.toHaveBeenCalled()
})
it('handles empty data from refetch', async () => {
const {WrappedComponent} = setupForSetRoutesTests({pathname: '/another-path'})
mockRefetch.mockResolvedValueOnce({
status: 'success',
data: undefined
})
render(<WrappedComponent />)
await act(async () => {
await navCallback?.({pathname: '/no-data-path'}, 'PUSH')
})
// Should not throw, and setRoutes should not be called
expect(setRoutesMock).not.toHaveBeenCalled()
})
it('does not call setRoutes if navCallback is not set', () => {
// navCallback is set by useBlockNavigation mock, so we can test the absence by not rendering
expect(navCallback).toBeDefined()
})
it('does not call refetch if urlSegment is falsy', async () => {
// Set up useLocation to return a falsy pathname
const {WrappedComponent} = setupForSetRoutesTests({pathname: ''})
render(<WrappedComponent />)
// Wait for effects to run
await waitFor(() => {
// refetch should not be called at all
expect(mockRefetch).not.toHaveBeenCalled()
})
})
})
})