-
Notifications
You must be signed in to change notification settings - Fork 400
/
helpers.js
530 lines (483 loc) · 14.9 KB
/
helpers.js
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
/* global Response */
import url from 'url';
import base64url from 'base64url';
import config, { util as configUtil } from 'config';
import { shallow } from 'enzyme';
import Jed from 'jed';
import { normalize } from 'normalizr';
import * as React from 'react';
import UAParser from 'ua-parser-js';
import { oneLine } from 'common-tags';
import { getDjangoBase62 } from 'amo/utils';
import * as coreApi from 'core/api';
import { ADDON_TYPE_EXTENSION, ADDON_TYPE_LANG } from 'core/constants';
import { makeI18n } from 'core/i18n/utils';
import { initialApiState } from 'core/reducers/api';
import { ErrorHandler } from 'core/errorHandler';
import { fakeAddon } from 'tests/unit/amo/helpers';
export const sampleUserAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1';
export const sampleUserAgentParsed = UAParser(sampleUserAgent);
export const randomId = () => {
// Add 1 to make sure it's never zero.
return Math.floor(Math.random() * 10000) + 1;
};
/*
* Return a fake authentication token that can be
* at least decoded in a realistic way.
*/
export function userAuthToken(
dataOverrides = {},
{ tokenCreatedAt = (Date.now() / 1000).toFixed(0), tokenData } = {},
) {
const data = {
user_id: 102345,
...dataOverrides,
};
let encodedToken = tokenData;
if (!encodedToken) {
encodedToken = base64url.encode(JSON.stringify(data));
}
const base62 = getDjangoBase62();
const timestamp = base62.encode(tokenCreatedAt);
const sig = base64url.encode('pretend-this-is-a-signature');
return `${encodedToken}:${timestamp}:${sig}`;
}
const enabledExtension = Promise.resolve({
isActive: true,
isEnabled: true,
type: ADDON_TYPE_EXTENSION,
});
export function getFakeAddonManagerWrapper({
getAddon = enabledExtension,
permissionPromptsEnabled = true,
...overrides
} = {}) {
return {
addChangeListeners: sinon.stub(),
enable: sinon.stub().returns(Promise.resolve()),
getAddon: sinon.stub().returns(getAddon),
install: sinon.stub().returns(Promise.resolve()),
uninstall: sinon.stub().returns(Promise.resolve()),
hasPermissionPromptsEnabled: sinon.stub().returns(permissionPromptsEnabled),
...overrides,
};
}
/*
* A promise resolution callback for expecting rejected promises.
*
* For example:
*
* return somePromiseThatShouldFail()
* .then(unexpectedSuccess, (error) => {
* expect(error.message).toMatch(/the error/);
* });
*/
export function unexpectedSuccess() {
return Promise.reject(new Error('The promise succeeded unexpectedly'));
}
export function JedSpy(data = {}) {
const _Jed = new Jed(data);
_Jed.gettext = sinon.spy(_Jed.gettext);
_Jed.dgettext = sinon.spy(_Jed.gettext);
_Jed.ngettext = sinon.spy(_Jed.ngettext);
_Jed.dngettext = sinon.spy(_Jed.dngettext);
_Jed.dpgettext = sinon.spy(_Jed.dpgettext);
_Jed.npgettext = sinon.spy(_Jed.npgettext);
_Jed.dnpgettext = sinon.spy(_Jed.dnpgettext);
_Jed.sprintf = sinon.spy(_Jed.sprintf);
return _Jed;
}
/*
* Creates a stand-in for a jed instance,
*/
export function fakeI18n({ lang = config.get('defaultLang') } = {}) {
return makeI18n({}, lang, JedSpy);
}
export class MockedSubComponent extends React.Component {
render() {
return <div />;
}
}
export function assertHasClass(el, className) {
expect(el.classList.contains(className)).toBeTruthy();
}
export function assertNotHasClass(el, className) {
expect(el.classList.contains(className)).toBeFalsy();
}
const { browser, os } = sampleUserAgentParsed;
export const signedInApiState = Object.freeze({
...initialApiState,
lang: 'en-US',
token: 'secret-token',
userAgent: sampleUserAgent,
userAgentInfo: { browser, os },
userId: 102345,
});
export const userAgentsByPlatform = {
android: {
firefox40Mobile: oneLine`Mozilla/5.0 (Android; Mobile; rv:40.0)
Gecko/40.0 Firefox/40.0`,
firefox40Tablet: oneLine`Mozilla/5.0 (Android; Tablet; rv:40.0)
Gecko/40.0 Firefox/40.0`,
},
bsd: {
firefox40FreeBSD: oneLine`Mozilla/5.0 (X11; FreeBSD amd64; rv:40.0)
Gecko/20100101 Firefox/40.0`,
},
firefoxOS: {
firefox26: 'Mozilla/5.0 (Mobile; rv:26.0) Gecko/26.0 Firefox/26.0',
},
ios: {
firefox1iPad: oneLine`Mozilla/5.0 (iPad; CPU iPhone OS 8_3
like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko)
FxiOS/1.0 Mobile/12F69 Safari/600.1.4`,
firefox1iPhone: oneLine`Mozilla/5.0 (iPhone; CPU iPhone OS 8_3
like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko)
FxiOS/1.0 Mobile/12F69n Safari/600.1.4`,
firefox1iPodTouch: oneLine`Mozilla/5.0 (iPod touch; CPU iPhone
OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko)
FxiOS/1.0 Mobile/12F69 Safari/600.1.4`,
},
linux: {
firefox10: oneLine`Mozilla/5.0 (X11; Linux i686; rv:10.0)
Gecko/20100101 Firefox/10.0`,
firefox57Ubuntu: oneLine`Mozilla/5.0 (X11; Ubuntu; Linux i686;
rv:57.0) Gecko/20100101 Firefox/57.0`,
},
mac: {
chrome41: oneLine`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36`,
firefox33: oneLine`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10;
rv:33.0) Gecko/20100101 Firefox/33.0`,
firefox57: oneLine`Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:57.0)
Gecko/20100101 Firefox/57.1`,
},
unix: {
firefox51: oneLine`Mozilla/51.0.2 (X11; Unix x86_64; rv:29.0)
Gecko/20170101 Firefox/51.0.2`,
},
windows: {
firefox40: oneLine`Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0)
Gecko/20100101 Firefox/40.1`,
},
};
export const userAgents = {
androidWebkit: [
oneLine`Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K)
AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30`,
oneLine`Mozilla/5.0 (Linux; U; Android 2.3.4; fr-fr; HTC Desire Build/GRJ22)
AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1`,
],
chromeAndroid: [
oneLine`Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C)
AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile
Safari/535.19`,
oneLine`Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76K)
AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile
Safari/535.19`,
oneLine`Mozilla/5.0 (Linux; Android 6.0.1; Nexus 6P Build/MMB29P)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.83 Mobile
Safari/537.36`,
],
chrome: [
oneLine`Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/41.0.2228.0 Safari/537.36`,
userAgentsByPlatform.mac.chrome41,
],
firefox: [
userAgentsByPlatform.linux.firefox10,
userAgentsByPlatform.windows.firefox40,
userAgentsByPlatform.mac.firefox33,
'Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0',
// Firefox ESR 52
oneLine`Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:52.2.1)
Gecko/20100101 Firefox/52.2.1`,
userAgentsByPlatform.mac.firefox57,
],
firefoxOS: [
userAgentsByPlatform.firefoxOS.firefox26,
'Mozilla/5.0 (Tablet; rv:26.0) Gecko/26.0 Firefox/26.0',
'Mozilla/5.0 (TV; rv:44.0) Gecko/44.0 Firefox/44.0',
'Mozilla/5.0 (Mobile; nnnn; rv:26.0) Gecko/26.0 Firefox/26.0',
],
firefoxAndroid: [
userAgentsByPlatform.android.firefox40Mobile,
userAgentsByPlatform.android.firefox40Tablet,
'Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0',
'Mozilla/5.0 (Android 4.4; Tablet; rv:41.0) Gecko/41.0 Firefox/41.0',
'Mozilla/5.0 (Android 4.4; Tablet; rv:57.0) Gecko/57.0 Firefox/57.0',
],
firefoxIOS: [
userAgentsByPlatform.ios.firefox1iPodTouch,
userAgentsByPlatform.ios.firefox1iPhone,
userAgentsByPlatform.ios.firefox1iPad,
],
};
export function apiResponsePage({
count, next, previous, pageSize = 25, results = [],
} = {}) {
return {
count: typeof count !== 'undefined' ? count : results.length,
next,
page_size: pageSize,
previous,
results,
};
}
export function createFetchAddonResult(addon) {
// Simulate how callApi() applies the add-on schema to
// the API server response.
return normalize(addon, coreApi.addon);
}
export function createFetchAllAddonsResult(addons) {
return normalize(
// Simulate an API response that returns an array of addons.
{ results: addons },
// Simulate how callApi() would apply an add-on schema to results.
{ results: [coreApi.addon] }
);
}
/*
* Repeatedly render a component tree using enzyme.shallow() until
* finding and rendering TargetComponent.
*
* This is useful for testing a component wrapped in one or more
* HOCs (higher order components).
*
* The `componentInstance` parameter is a React component instance.
* Example: <MyComponent {...props} />
*
* The `TargetComponent` parameter is the React class (or function) that
* you want to retrieve from the component tree.
*/
export function shallowUntilTarget(componentInstance, TargetComponent, {
maxTries = 10,
shallowOptions,
_shallow = shallow,
} = {}) {
if (!componentInstance) {
throw new Error('componentInstance parameter is required');
}
if (!TargetComponent) {
throw new Error('TargetComponent parameter is required');
}
let root = _shallow(componentInstance, shallowOptions);
if (typeof root.type() === 'string') {
// If type() is a string then it's a DOM Node.
// If it were wrapped, it would be a React component.
throw new Error(
'Cannot unwrap this component because it is not wrapped');
}
for (let tries = 1; tries <= maxTries; tries++) {
if (root.is(TargetComponent)) {
// Now that we found the target component, render it.
return root.shallow(shallowOptions);
}
// Unwrap the next component in the hierarchy.
root = root.dive();
}
throw new Error(oneLine`Could not find ${TargetComponent} in rendered
instance: ${componentInstance}; gave up after ${maxTries} tries`
);
}
export function createFakeEvent(extraProps = {}) {
return {
currentTarget: sinon.stub(),
preventDefault: sinon.stub(),
stopPropagation: sinon.stub(),
...extraProps,
};
}
export const createFakeMozWindow = () => {
// This is a special Mozilla window that allows you to
// install open search add-ons.
return { external: { AddSearchProvider: sinon.stub() } };
};
export function createStubErrorHandler(capturedError = null) {
return new ErrorHandler({
id: 'create-stub-error-handler-id',
dispatch: sinon.stub(),
capturedError,
});
}
export function generateHeaders(
headerData = { 'Content-Type': 'application/json' }
) {
const response = new Response();
Object.keys(headerData).forEach((key) => (
response.headers.append(key, headerData[key])
));
return response.headers;
}
export function createApiResponse({
ok = true, jsonData = {}, ...responseProps
} = {}) {
const response = {
ok,
headers: generateHeaders(),
json: () => Promise.resolve(jsonData),
...responseProps,
};
return Promise.resolve(response);
}
export function createFakeLanguageTool(otherProps = {}) {
return {
id: fakeAddon.id,
current_version: fakeAddon.current_version,
default_locale: 'en-US',
guid: fakeAddon.guid,
locale_disambiguation: '',
name: fakeAddon.name,
target_locale: 'ach',
type: ADDON_TYPE_LANG,
url: 'https://addons.allizom.org/en-US/firefox/addon/acholi-ug-lp-test',
...otherProps,
};
}
export function createUserAccountResponse({
id = 123456,
biography = 'I love making add-ons!',
username = 'user-1234',
created = '2017-08-15T12:01:13Z',
/* eslint-disable camelcase */
average_addon_rating = 4.3,
display_name = null,
num_addons_listed = 1,
picture_url = `${config.get('amoCDN')}/static/img/zamboni/anon_user.png`,
picture_type = '',
/* eslint-enable camelcase */
homepage = null,
permissions = [],
} = {}) {
return {
average_addon_rating,
biography,
created,
display_name,
homepage,
id,
is_addon_developer: false,
is_artist: false,
location: '',
name: '',
num_addons_listed,
occupation: '',
picture_type,
picture_url,
url: null,
username,
permissions,
};
}
export function createFakeAddonAbuseReport({
addon = fakeAddon,
message,
reporter = null,
} = {}) {
return {
addon: {
guid: addon.guid,
id: addon.id,
slug: addon.slug,
},
message,
reporter,
};
}
export function createFakeUserAbuseReport({
message,
reporter = null,
user = createUserAccountResponse(),
} = {}) {
return {
message,
reporter,
user: {
id: user.id,
name: user.name,
url: user.url,
username: user.username,
},
};
}
// Returns a real-ish config object with custom parameters.
//
// Example:
//
// const fakeConfig = getFakeConfig({ isDevelopment: true });
// if (fakeConfig.get('isDevelopment')) {
// ...
// }
export const getFakeConfig = (params = {}) => {
for (const key of Object.keys(params)) {
if (!config.has(key)) {
// This will help alert us when a test accidentally relies
// on an invalid config key.
throw new Error(
`Cannot set a fake value for "${key}"; this key is invalid`);
}
}
return Object.assign(configUtil.cloneDeep(config), params);
};
/*
* A sinon matcher to check if the URL contains the declared params.
*
* Example:
*
* mockWindow.expects('fetch').withArgs(urlWithTheseParams({ page: 1 }))
*/
export const urlWithTheseParams = (params) => {
return sinon.match((urlString) => {
const { query } = url.parse(urlString, true);
for (const param in params) {
if (!query[param] || query[param] !== params[param].toString()) {
return false;
}
}
return true;
}, `urlWithTheseParams(${JSON.stringify(params)})`);
};
/*
* Returns a fake ReactRouter location object.
*
* See ReactRouterLocation in 'core/types/router';
*/
export const fakeRouterLocation = (props = {}) => {
return {
action: 'PUSH',
hash: '',
key: 'some-key',
pathname: '/some/url',
query: {},
search: '',
...props,
};
};
/*
* Simulate how a component you depend on will invoke a callback.
*
* The return value is an executable callback that you can call
* with the necessary arguments.
*
* type SimulateComponentCallbackParams = {|
* // This is the root of your parent component (an enzyme wrapper object).
* root: Object,
* // This is the component class you want to simulate.
* Component: React.Element<any>,
* // This is the property name for the callback.
* propName: string,
* |};
*/
export const simulateComponentCallback = ({ Component, root, propName }) => {
const component = root.find(Component);
expect(component).toHaveProp(propName);
const callback = component.prop(propName);
expect(typeof callback).toEqual('function');
return (...args) => {
const result = callback(...args);
// Since the component might call setState() and that would happen
// outside of a standard React lifestyle hook, we have to re-render.
root.update();
return result;
};
};