-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathtestUtils.tsx
205 lines (192 loc) · 6.46 KB
/
testUtils.tsx
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
/* istanbul ignore file */
/* eslint-disable react/prop-types */
/* eslint-disable import/no-extraneous-dependencies */
/**
* Helper functions for writing tests.
*/
import React from 'react';
import { AxiosError } from 'axios';
import { jest } from '@jest/globals';
import type { Store } from 'redux';
import { initializeMockApp } from '@edx/frontend-platform';
import { getAuthenticatedHttpClient } from '@edx/frontend-platform/auth';
import { IntlProvider } from '@edx/frontend-platform/i18n';
import { AppProvider } from '@edx/frontend-platform/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, type RenderResult } from '@testing-library/react';
import MockAdapter from 'axios-mock-adapter';
import {
MemoryRouter,
MemoryRouterProps,
Route,
Routes,
} from 'react-router-dom';
import { ToastContext, type ToastContextData } from './generic/toast-context';
import initializeReduxStore from './store';
/** @deprecated Use React Query and/or regular React Context instead of redux */
let reduxStore: Store;
let queryClient;
let axiosMock: MockAdapter;
/** To use this: `const { mockShowToast } = initializeMocks()` and `expect(mockShowToast).toHaveBeenCalled()` */
let mockToastContext: ToastContextData = {
showToast: jest.fn(),
closeToast: jest.fn(),
toastMessage: null,
};
export interface RouteOptions {
/** The URL path, like '/libraries/:libraryId' */
path?: string;
/** The URL parameters, like {libraryId: 'lib:org:123'} */
params?: Record<string, string>;
/** and/or instead of specifying path and params, specify MemoryRouterProps */
routerProps?: MemoryRouterProps;
}
/**
* This component works together with the custom `render()` method we have in
* this file to provide whatever react-router context you need for your
* component.
*
* In the simplest case, you don't need to worry about the router at all, so
* just render your component using `render(<TheComponent />)`.
*
* The next simplest way to use it is to specify `path` (the route matching rule
* that is normally used to determine when to show the component or its parent
* page) and `params` like this:
*
* ```
* render(<LibraryLayout />, { path: '/library/:libraryId/*', params: { libraryId: 'lib:Axim:testlib' } });
* ```
*
* In this case, components that use the `useParams` hook will get the right
* library ID, and we don't even have to mock anything.
*
* In other cases, such as when you have routes inside routes, you'll need to
* set the router's `initialEntries` (URL history) prop yourself, like this:
*
* ```
* render(<LibraryLayout />, {
* path: '/library/:libraryId/*',
* // The root component is mounted on the above path, as it is in the "real"
* // MFE. But to access the 'settings' sub-route/component for this test, we
* // need tospecify the URL like this:
* routerProps: { initialEntries: [`/library/${libraryId}/settings`] },
* });
* ```
*/
const RouterAndRoute: React.FC<RouteOptions> = ({
children,
path = '/',
params = {},
routerProps = {},
}) => {
if (Object.entries(params).length > 0 || path !== '/') {
const newRouterProps = { ...routerProps };
if (!routerProps.initialEntries) {
// Substitute the params into the URL so '/library/:libraryId' becomes '/library/lib:org:123'
let pathWithParams = path;
for (const [key, value] of Object.entries(params)) {
pathWithParams = pathWithParams.replaceAll(`:${key}`, value);
}
if (pathWithParams.endsWith('/*')) {
// Some routes (that contain child routes) need to end with /* in the <Route> but not in the router
pathWithParams = pathWithParams.substring(0, pathWithParams.length - 1);
}
newRouterProps.initialEntries = [pathWithParams];
}
return (
<MemoryRouter {...newRouterProps}>
<Routes>
<Route path={path} element={children} />
</Routes>
</MemoryRouter>
);
}
return (
<MemoryRouter {...routerProps}>{children}</MemoryRouter>
);
};
function makeWrapper({ ...routeArgs }: RouteOptions) {
const AllTheProviders = ({ children }) => (
<AppProvider store={reduxStore} wrapWithRouter={false}>
<IntlProvider locale="en" messages={{}}>
<QueryClientProvider client={queryClient}>
<ToastContext.Provider value={mockToastContext}>
<RouterAndRoute {...routeArgs}>
{children}
</RouterAndRoute>
</ToastContext.Provider>
</QueryClientProvider>
</IntlProvider>
</AppProvider>
);
return AllTheProviders;
}
/**
* Same as render() from `@testing-library/react` but this one provides all the
* wrappers our React components need to render properly.
*/
function customRender(ui: React.ReactElement, options: RouteOptions = {}): RenderResult {
return render(ui, { wrapper: makeWrapper(options) });
}
const defaultUser = {
userId: 3,
username: 'abc123',
administrator: true,
roles: [],
} as const;
/**
* Initialize common mocks that many of our React components will require.
*
* This should be called within each test case, or in `beforeEach()`.
*
* Returns the new `axiosMock` in case you need to mock out axios requests.
*/
export function initializeMocks({ user = defaultUser, initialState = undefined }: {
user?: { userId: number, username: string },
initialState?: Record<string, any>, // TODO: proper typing for our redux state
} = {}) {
initializeMockApp({
authenticatedUser: user,
});
reduxStore = initializeReduxStore(initialState as any);
queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
});
axiosMock = new MockAdapter(getAuthenticatedHttpClient());
// Reset `mockToastContext` for this current test
mockToastContext = {
showToast: jest.fn(),
closeToast: jest.fn(),
toastMessage: null,
};
return {
reduxStore,
axiosMock,
mockShowToast: mockToastContext.showToast,
};
}
export * from '@testing-library/react';
export { customRender as render };
/** Simulate a real Axios error (such as we'd see in response to a 404) */
export function createAxiosError({ code, message, path }: { code: number, message: string, path: string }) {
const request = { path };
const config = {};
const error = new AxiosError(
`Mocked request failed with status code ${code}`,
AxiosError.ERR_BAD_RESPONSE,
config,
request,
{
status: code,
data: { detail: message },
statusText: 'error',
config,
headers: {},
},
);
return error;
}