forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTestHelper.ts
321 lines (290 loc) · 11.6 KB
/
TestHelper.ts
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
import {Str} from 'expensify-common';
import {Linking} from 'react-native';
import Onyx from 'react-native-onyx';
import type {ApiCommand, ApiRequestCommandParameters} from '@libs/API/types';
import * as Pusher from '@libs/Pusher/pusher';
import PusherConnectionManager from '@libs/PusherConnectionManager';
import CONFIG from '@src/CONFIG';
import CONST from '@src/CONST';
import * as Session from '@src/libs/actions/Session';
import HttpUtils from '@src/libs/HttpUtils';
import * as NumberUtils from '@src/libs/NumberUtils';
import ONYXKEYS from '@src/ONYXKEYS';
import appSetup from '@src/setup';
import type {Response as OnyxResponse, PersonalDetails, Report} from '@src/types/onyx';
import waitForBatchedUpdates from './waitForBatchedUpdates';
type MockFetch = jest.MockedFn<typeof fetch> & {
pause: () => void;
fail: () => void;
succeed: () => void;
resume: () => Promise<void>;
mockAPICommand: <TCommand extends ApiCommand>(command: TCommand, responseHandler: (params: ApiRequestCommandParameters[TCommand]) => OnyxResponse['onyxData']) => void;
};
type QueueItem = {
resolve: (value: Partial<Response> | PromiseLike<Partial<Response>>) => void;
input: RequestInfo;
options?: RequestInit;
};
type FormData = {
entries: () => Array<[string, string | Blob]>;
};
function setupApp() {
beforeAll(() => {
Linking.setInitialURL('https://new.expensify.com/');
appSetup();
// Connect to Pusher
PusherConnectionManager.init();
Pusher.init({
appKey: CONFIG.PUSHER.APP_KEY,
cluster: CONFIG.PUSHER.CLUSTER,
authEndpoint: `${CONFIG.EXPENSIFY.DEFAULT_API_ROOT}api/AuthenticatePusher?`,
});
});
}
function buildPersonalDetails(login: string, accountID: number, firstName = 'Test'): PersonalDetails {
return {
accountID,
login,
avatar: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/avatar_7.png',
avatarThumbnail: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/avatar_7.png',
displayName: `${firstName} User`,
firstName,
lastName: 'User',
pronouns: '',
timezone: CONST.DEFAULT_TIME_ZONE,
phoneNumber: '',
};
}
/**
* Simulate signing in and make sure all API calls in this flow succeed. Every time we add
* a mockImplementationOnce() we are altering what Network.post() will return.
*/
function signInWithTestUser(accountID = 1, login = '[email protected]', password = 'Password1', authToken = 'asdfqwerty', firstName = 'Test') {
const originalXhr = HttpUtils.xhr;
HttpUtils.xhr = jest.fn().mockImplementation(() => {
const mockedResponse: OnyxResponse = {
onyxData: [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.CREDENTIALS,
value: {
login,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
validated: true,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
value: {
[accountID]: buildPersonalDetails(login, accountID, firstName),
},
},
],
jsonCode: 200,
};
// Return a Promise that resolves with the mocked response
return Promise.resolve(mockedResponse);
});
// Simulate user entering their login and populating the credentials.login
Session.beginSignIn(login);
return waitForBatchedUpdates()
.then(() => {
HttpUtils.xhr = jest.fn().mockImplementation(() => {
const mockedResponse: OnyxResponse = {
onyxData: [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.SESSION,
value: {
authToken,
accountID,
email: login,
encryptedAuthToken: authToken,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.CREDENTIALS,
value: {
autoGeneratedLogin: Str.guid('expensify.cash-'),
autoGeneratedPassword: Str.guid(),
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.USER,
value: {
isUsingExpensifyCard: false,
},
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.BETAS,
value: ['all'],
},
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.NVP_PRIVATE_PUSH_NOTIFICATION_ID,
value: 'randomID',
},
],
jsonCode: 200,
};
// Return a Promise that resolves with the mocked response
return Promise.resolve(mockedResponse);
});
Session.signIn(password);
return waitForBatchedUpdates();
})
.then(() => {
HttpUtils.xhr = originalXhr;
});
}
function signOutTestUser() {
const originalXhr = HttpUtils.xhr;
HttpUtils.xhr = jest.fn().mockImplementation(() => {
const mockedResponse: OnyxResponse = {
jsonCode: 200,
};
// Return a Promise that resolves with the mocked response
return Promise.resolve(mockedResponse);
});
Session.signOutAndRedirectToSignIn();
return waitForBatchedUpdates().then(() => (HttpUtils.xhr = originalXhr));
}
/**
* Use for situations where fetch() is required. This mock is stateful and has some additional methods to control its behavior:
*
* - pause() – stop resolving promises until you call resume()
* - resume() - flush the queue of promises, and start resolving new promises immediately
* - fail() - start returning a failure response
* - success() - go back to returning a success response
*/
function getGlobalFetchMock(): typeof fetch {
let queue: QueueItem[] = [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let responses = new Map<string, (params: any) => OnyxResponse['onyxData']>();
let isPaused = false;
let shouldFail = false;
const getResponse = (input: RequestInfo, options?: RequestInit): Partial<Response> =>
shouldFail
? {
ok: true,
json: () => Promise.resolve({jsonCode: 400}),
}
: {
ok: true,
json: async () => {
const commandMatch = typeof input === 'string' ? input.match(/https:\/\/www.expensify.com.dev\/api\/(\w+)\?/) : null;
const command = commandMatch ? commandMatch[1] : null;
const responseHandler = command ? responses.get(command) : null;
if (responseHandler) {
const requestData = options?.body instanceof FormData ? Object.fromEntries(options.body) : {};
return Promise.resolve({jsonCode: 200, onyxData: responseHandler(requestData)});
}
return Promise.resolve({jsonCode: 200});
},
};
const mockFetch = jest.fn().mockImplementation((input: RequestInfo, options?: RequestInit) => {
if (!isPaused) {
return Promise.resolve(getResponse(input, options));
}
return new Promise((resolve) => {
queue.push({resolve, input, options});
});
}) as MockFetch;
const baseMockReset = mockFetch.mockReset.bind(mockFetch);
mockFetch.mockReset = () => {
baseMockReset();
queue = [];
responses = new Map();
isPaused = false;
shouldFail = false;
return mockFetch;
};
mockFetch.pause = () => (isPaused = true);
mockFetch.resume = () => {
isPaused = false;
queue.forEach(({resolve, input}) => resolve(getResponse(input)));
return waitForBatchedUpdates();
};
mockFetch.fail = () => (shouldFail = true);
mockFetch.succeed = () => (shouldFail = false);
mockFetch.mockAPICommand = <TCommand extends ApiCommand>(command: TCommand, responseHandler: (params: ApiRequestCommandParameters[TCommand]) => OnyxResponse['onyxData']): void => {
responses.set(command, responseHandler);
};
return mockFetch as typeof fetch;
}
function setupGlobalFetchMock(): MockFetch {
const mockFetch = getGlobalFetchMock();
const originalFetch = global.fetch;
global.fetch = mockFetch as unknown as typeof global.fetch;
afterAll(() => {
global.fetch = originalFetch;
});
return mockFetch as MockFetch;
}
function getFetchMockCalls(commandName: ApiCommand) {
return (global.fetch as MockFetch).mock.calls.filter((c) => c[0] === `https://www.expensify.com.dev/api/${commandName}?`);
}
/**
* Assertion helper to validate that a command has been called a specific number of times.
*/
function expectAPICommandToHaveBeenCalled(commandName: ApiCommand, expectedCalls: number) {
expect(getFetchMockCalls(commandName)).toHaveLength(expectedCalls);
}
/**
* Assertion helper to validate that a command has been called with specific parameters.
*/
function expectAPICommandToHaveBeenCalledWith<TCommand extends ApiCommand>(commandName: TCommand, callIndex: number, expectedParams: ApiRequestCommandParameters[TCommand]) {
const call = getFetchMockCalls(commandName).at(callIndex);
expect(call).toBeTruthy();
const body = (call?.at(1) as RequestInit)?.body;
const params = body instanceof FormData ? Object.fromEntries(body) : {};
expect(params).toEqual(expect.objectContaining(expectedParams));
}
function setPersonalDetails(login: string, accountID: number) {
Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {
[accountID]: buildPersonalDetails(login, accountID),
});
return waitForBatchedUpdates();
}
function buildTestReportComment(created: string, actorAccountID: number, actionID: string | null = null) {
const reportActionID = actionID ?? NumberUtils.rand64().toString();
return {
actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT,
person: [{type: 'TEXT', style: 'strong', text: 'User B'}],
created,
message: [{type: 'COMMENT', html: `Comment ${actionID}`, text: `Comment ${actionID}`}],
reportActionID,
actorAccountID,
};
}
function assertFormDataMatchesObject(formData: FormData, obj: Report) {
expect(
Array.from(formData.entries()).reduce((acc, [key, val]) => {
acc[key] = val;
return acc;
}, {} as Record<string, string | Blob>),
).toEqual(expect.objectContaining(obj));
}
export type {MockFetch, FormData};
export {
assertFormDataMatchesObject,
buildPersonalDetails,
buildTestReportComment,
getGlobalFetchMock,
setPersonalDetails,
signInWithTestUser,
signOutTestUser,
setupApp,
expectAPICommandToHaveBeenCalled,
expectAPICommandToHaveBeenCalledWith,
setupGlobalFetchMock,
};