forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathinspectElement-test.js
More file actions
500 lines (420 loc) · 14.6 KB
/
inspectElement-test.js
File metadata and controls
500 lines (420 loc) · 14.6 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
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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {InspectedElementPayload} from 'react-devtools-shared/src/backend/types';
import type {DehydratedData} from 'react-devtools-shared/src/devtools/views/Components/types';
import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type Store from 'react-devtools-shared/src/devtools/store';
describe('InspectedElementContext', () => {
let React;
let ReactDOM;
let hydrate;
let meta;
let bridge: FrontendBridge;
let store: Store;
const act = (callback: Function) => {
callback();
jest.runAllTimers(); // Flush Bridge operations
};
function dehydrateHelper(
dehydratedData: DehydratedData | null,
): Object | null {
if (dehydratedData !== null) {
return hydrate(
dehydratedData.data,
dehydratedData.cleaned,
dehydratedData.unserializable,
);
} else {
return null;
}
}
async function read(
id: number,
path?: Array<string | number>,
): Promise<Object> {
return new Promise((resolve, reject) => {
const rendererID = ((store.getRendererIDForElement(id): any): number);
const onInspectedElement = (payload: InspectedElementPayload) => {
bridge.removeListener('inspectedElement', onInspectedElement);
if (payload.type === 'full-data' && payload.value !== null) {
payload.value.context = dehydrateHelper(payload.value.context);
payload.value.props = dehydrateHelper(payload.value.props);
payload.value.state = dehydrateHelper(payload.value.state);
}
resolve(payload);
};
bridge.addListener('inspectedElement', onInspectedElement);
bridge.send('inspectElement', {id, path, rendererID});
jest.runOnlyPendingTimers();
});
}
beforeEach(() => {
bridge = global.bridge;
store = global.store;
hydrate = require('react-devtools-shared/src/hydration').hydrate;
meta = require('react-devtools-shared/src/hydration').meta;
// Redirect all React/ReactDOM requires to the v15 UMD.
// We use the UMD because Jest doesn't enable us to mock deep imports (e.g. "react/lib/Something").
jest.mock('react', () => jest.requireActual('react-15/dist/react.js'));
jest.mock('react-dom', () =>
jest.requireActual('react-dom-15/dist/react-dom.js'),
);
React = require('react');
ReactDOM = require('react-dom');
});
it('should inspect the currently selected element', async done => {
const Example = () => null;
act(() =>
ReactDOM.render(<Example a={1} b="abc" />, document.createElement('div')),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement).toMatchSnapshot('1: Initial inspection');
done();
});
it('should support simple data types', async done => {
const Example = () => null;
act(() =>
ReactDOM.render(
<Example
boolean_false={false}
boolean_true={true}
infinity={Infinity}
integer_zero={0}
integer_one={1}
float={1.23}
string="abc"
string_empty=""
nan={NaN}
value_null={null}
value_undefined={undefined}
/>,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement).toMatchSnapshot('1: Initial inspection');
const {props} = inspectedElement.value;
expect(props.boolean_false).toBe(false);
expect(props.boolean_true).toBe(true);
expect(Number.isFinite(props.infinity)).toBe(false);
expect(props.integer_zero).toEqual(0);
expect(props.integer_one).toEqual(1);
expect(props.float).toEqual(1.23);
expect(props.string).toEqual('abc');
expect(props.string_empty).toEqual('');
expect(props.nan).toBeNaN();
expect(props.value_null).toBeNull();
expect(props.value_undefined).toBeUndefined();
done();
});
it('should support complex data types', async done => {
const Immutable = require('immutable');
const Example = () => null;
const arrayOfArrays = [[['abc', 123, true], []]];
const div = document.createElement('div');
const exampleFunction = () => {};
const setShallow = new Set(['abc', 123]);
const mapShallow = new Map([['name', 'Brian'], ['food', 'sushi']]);
const setOfSets = new Set([new Set(['a', 'b', 'c']), new Set([1, 2, 3])]);
const mapOfMaps = new Map([['first', mapShallow], ['second', mapShallow]]);
const objectOfObjects = {
inner: {string: 'abc', number: 213, boolean: true},
};
const typedArray = Int8Array.from([100, -100, 0]);
const arrayBuffer = typedArray.buffer;
const dataView = new DataView(arrayBuffer);
const immutableMap = Immutable.fromJS({
a: [{hello: 'there'}, 'fixed', true],
b: 123,
c: {
'1': 'xyz',
xyz: 1,
},
});
act(() =>
ReactDOM.render(
<Example
array_buffer={arrayBuffer}
array_of_arrays={arrayOfArrays}
// eslint-disable-next-line no-undef
big_int={BigInt(123)}
data_view={dataView}
date={new Date(123)}
fn={exampleFunction}
html_element={div}
immutable={immutableMap}
map={mapShallow}
map_of_maps={mapOfMaps}
object_of_objects={objectOfObjects}
react_element={<span />}
set={setShallow}
set_of_sets={setOfSets}
symbol={Symbol('symbol')}
typed_array={typedArray}
/>,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement).toMatchSnapshot('1: Initial inspection');
const {
array_buffer,
array_of_arrays,
big_int,
data_view,
date,
fn,
html_element,
immutable,
map,
map_of_maps,
object_of_objects,
react_element,
set,
set_of_sets,
symbol,
typed_array,
} = inspectedElement.value.props;
expect(array_buffer[meta.size]).toBe(3);
expect(array_buffer[meta.inspectable]).toBe(false);
expect(array_buffer[meta.name]).toBe('ArrayBuffer');
expect(array_buffer[meta.type]).toBe('array_buffer');
expect(array_buffer[meta.preview_short]).toBe('ArrayBuffer(3)');
expect(array_buffer[meta.preview_long]).toBe('ArrayBuffer(3)');
expect(array_of_arrays[0][meta.size]).toBe(2);
expect(array_of_arrays[0][meta.inspectable]).toBe(true);
expect(array_of_arrays[0][meta.name]).toBe('Array');
expect(array_of_arrays[0][meta.type]).toBe('array');
expect(array_of_arrays[0][meta.preview_long]).toBe('[Array(3), Array(0)]');
expect(array_of_arrays[0][meta.preview_short]).toBe('Array(2)');
expect(big_int[meta.inspectable]).toBe(false);
expect(big_int[meta.name]).toBe('123');
expect(big_int[meta.type]).toBe('bigint');
expect(data_view[meta.size]).toBe(3);
expect(data_view[meta.inspectable]).toBe(false);
expect(data_view[meta.name]).toBe('DataView');
expect(data_view[meta.type]).toBe('data_view');
expect(date[meta.inspectable]).toBe(false);
expect(date[meta.type]).toBe('date');
expect(fn[meta.inspectable]).toBe(false);
expect(fn[meta.name]).toBe('exampleFunction');
expect(fn[meta.type]).toBe('function');
expect(html_element[meta.inspectable]).toBe(false);
expect(html_element[meta.name]).toBe('DIV');
expect(html_element[meta.type]).toBe('html_element');
expect(immutable[meta.inspectable]).toBeUndefined(); // Complex type
expect(immutable[meta.name]).toBe('Map');
expect(immutable[meta.type]).toBe('iterator');
expect(map[meta.inspectable]).toBeUndefined(); // Complex type
expect(map[meta.name]).toBe('Map');
expect(map[meta.type]).toBe('iterator');
expect(map[0][meta.type]).toBe('array');
expect(map_of_maps[meta.inspectable]).toBeUndefined(); // Complex type
expect(map_of_maps[meta.name]).toBe('Map');
expect(map_of_maps[meta.type]).toBe('iterator');
expect(map_of_maps[0][meta.type]).toBe('array');
expect(object_of_objects.inner[meta.size]).toBe(3);
expect(object_of_objects.inner[meta.inspectable]).toBe(true);
expect(object_of_objects.inner[meta.name]).toBe('');
expect(object_of_objects.inner[meta.type]).toBe('object');
expect(object_of_objects.inner[meta.preview_long]).toBe(
'{boolean: true, number: 213, string: "abc"}',
);
expect(object_of_objects.inner[meta.preview_short]).toBe('{…}');
expect(react_element[meta.inspectable]).toBe(false);
expect(react_element[meta.name]).toBe('span');
expect(react_element[meta.type]).toBe('react_element');
expect(set[meta.inspectable]).toBeUndefined(); // Complex type
expect(set[meta.name]).toBe('Set');
expect(set[meta.type]).toBe('iterator');
expect(set[0]).toBe('abc');
expect(set[1]).toBe(123);
expect(set_of_sets[meta.inspectable]).toBeUndefined(); // Complex type
expect(set_of_sets[meta.name]).toBe('Set');
expect(set_of_sets[meta.type]).toBe('iterator');
expect(set_of_sets['0'][meta.inspectable]).toBe(true);
expect(symbol[meta.inspectable]).toBe(false);
expect(symbol[meta.name]).toBe('Symbol(symbol)');
expect(symbol[meta.type]).toBe('symbol');
expect(typed_array[meta.inspectable]).toBeUndefined(); // Complex type
expect(typed_array[meta.size]).toBe(3);
expect(typed_array[meta.name]).toBe('Int8Array');
expect(typed_array[meta.type]).toBe('typed_array');
expect(typed_array[0]).toBe(100);
expect(typed_array[1]).toBe(-100);
expect(typed_array[2]).toBe(0);
done();
});
it('should support custom objects with enumerable properties and getters', async done => {
class CustomData {
_number = 42;
get number() {
return this._number;
}
set number(value) {
this._number = value;
}
}
const descriptor = ((Object.getOwnPropertyDescriptor(
CustomData.prototype,
'number',
): any): PropertyDescriptor<number>);
descriptor.enumerable = true;
Object.defineProperty(CustomData.prototype, 'number', descriptor);
const Example = ({data}) => null;
act(() =>
ReactDOM.render(
<Example data={new CustomData()} />,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const inspectedElement = await read(id);
expect(inspectedElement).toMatchSnapshot('1: Initial inspection');
done();
});
it('should not dehydrate nested values until explicitly requested', async done => {
const Example = () => null;
act(() =>
ReactDOM.render(
<Example
nestedObject={{
a: {
b: {
c: [
{
d: {
e: {},
},
},
],
},
},
}}
/>,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
let inspectedElement = await read(id);
expect(inspectedElement).toMatchSnapshot('1: Initially inspect element');
inspectedElement = await read(id, ['props', 'nestedObject', 'a']);
expect(inspectedElement).toMatchSnapshot('2: Inspect props.nestedObject.a');
inspectedElement = await read(id, ['props', 'nestedObject', 'a', 'b', 'c']);
expect(inspectedElement).toMatchSnapshot(
'3: Inspect props.nestedObject.a.b.c',
);
inspectedElement = await read(id, [
'props',
'nestedObject',
'a',
'b',
'c',
0,
'd',
]);
expect(inspectedElement).toMatchSnapshot(
'4: Inspect props.nestedObject.a.b.c.0.d',
);
done();
});
it('should enable inspected values to be stored as global variables', () => {
const Example = () => null;
const nestedObject = {
a: {
value: 1,
b: {
value: 1,
c: {
value: 1,
},
},
},
};
act(() =>
ReactDOM.render(
<Example nestedObject={nestedObject} />,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const rendererID = ((store.getRendererIDForElement(id): any): number);
const logSpy = jest.fn();
spyOn(console, 'log').and.callFake(logSpy);
// Should store the whole value (not just the hydrated parts)
bridge.send('storeAsGlobal', {
count: 1,
id,
path: ['props', 'nestedObject'],
rendererID,
});
jest.runOnlyPendingTimers();
expect(logSpy).toHaveBeenCalledWith('$reactTemp1');
expect(global.$reactTemp1).toBe(nestedObject);
logSpy.mockReset();
// Should store the nested property specified (not just the outer value)
bridge.send('storeAsGlobal', {
count: 2,
id,
path: ['props', 'nestedObject', 'a', 'b'],
rendererID,
});
jest.runOnlyPendingTimers();
expect(logSpy).toHaveBeenCalledWith('$reactTemp2');
expect(global.$reactTemp2).toBe(nestedObject.a.b);
});
it('should enable inspected values to be copied to the clipboard', () => {
const Example = () => null;
const nestedObject = {
a: {
value: 1,
b: {
value: 1,
c: {
value: 1,
},
},
},
};
act(() =>
ReactDOM.render(
<Example nestedObject={nestedObject} />,
document.createElement('div'),
),
);
const id = ((store.getElementIDAtIndex(0): any): number);
const rendererID = ((store.getRendererIDForElement(id): any): number);
// Should copy the whole value (not just the hydrated parts)
bridge.send('copyElementPath', {
id,
path: ['props', 'nestedObject'],
rendererID,
});
jest.runOnlyPendingTimers();
expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1);
expect(global.mockClipboardCopy).toHaveBeenCalledWith(
JSON.stringify(nestedObject),
);
global.mockClipboardCopy.mockReset();
// Should copy the nested property specified (not just the outer value)
bridge.send('copyElementPath', {
id,
path: ['props', 'nestedObject', 'a', 'b'],
rendererID,
});
jest.runOnlyPendingTimers();
expect(global.mockClipboardCopy).toHaveBeenCalledTimes(1);
expect(global.mockClipboardCopy).toHaveBeenCalledWith(
JSON.stringify(nestedObject.a.b),
);
});
});