-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathobject.test.ts
460 lines (377 loc) · 12.7 KB
/
object.test.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
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
/**
* @vitest-environment jsdom
*/
import type { WrappedFunction } from '../../src/types-hoist';
import { describe, expect, it, test, vi } from 'vitest';
import {
addNonEnumerableProperty,
dropUndefinedKeys,
extractExceptionKeysForMessage,
fill,
markFunctionWrapped,
objectify,
} from '../../src/utils-hoist/object';
import { testOnlyIfNodeVersionAtLeast } from './testutils';
describe('fill()', () => {
test('wraps a method by calling a replacement function on it', () => {
const source = {
foo(): number {
return 42;
},
};
const name = 'foo';
const replacement = vi.fn().mockImplementationOnce(cb => cb);
fill(source, name, replacement);
expect(source.foo()).toEqual(42);
expect(replacement).toBeCalled();
});
test('does not throw on readonly properties', () => {
const originalFn = () => 41;
const source = {
get prop() {
return originalFn;
},
set prop(_fn: () => number) {
throw new Error('OH NO, this is not writeable...');
},
};
expect(source.prop()).toEqual(41);
const replacement = vi.fn().mockImplementation(() => {
return () => 42;
});
fill(source, 'prop', replacement);
expect(replacement).toBeCalled();
expect(source.prop).toBe(originalFn);
expect(source.prop()).toEqual(41);
});
test.each([42, null, undefined, {}])("does't throw if the property is not a function but %s", (propValue: any) => {
const source = {
foo: propValue,
};
const name = 'foo';
const replacement = vi.fn().mockImplementationOnce(cb => cb);
fill(source, name, replacement);
expect(source.foo).toBe(propValue);
expect(replacement).not.toBeCalled();
});
test('can do anything inside replacement function', () => {
const source = {
foo: (): number => 42,
};
const name = 'foo';
const replacement = vi.fn().mockImplementationOnce(cb => {
expect(cb).toBe(source.foo);
return () => 1337;
});
fill(source, name, replacement);
expect(source.foo()).toEqual(1337);
expect(replacement).toBeCalled();
expect.assertions(3);
});
test('multiple fills calls all functions', () => {
const source = {
foo: (): number => 42,
};
const name = 'foo';
const replacement = vi.fn().mockImplementationOnce(cb => {
expect(cb).toBe(source.foo);
return () => 1337;
});
const replacement2 = vi.fn().mockImplementationOnce(cb => {
expect(cb).toBe(source.foo);
return () => 1338;
});
fill(source, name, replacement);
fill(source, name, replacement2);
expect(source.foo()).toEqual(1338);
expect(replacement).toBeCalled();
expect(replacement2).toBeCalled();
expect.assertions(5);
});
test('internal flags shouldnt be enumerable', () => {
const source = {
foo: (): number => 42,
} as any;
const name = 'foo';
// @ts-expect-error cb has any type
const replacement = cb => cb;
fill(source, name, replacement);
// Shouldn't show up in iteration
expect(Object.keys(replacement)).not.toContain('__sentry_original__');
// But should be accessible directly
expect(source.foo.__sentry_original__).toBe(source.foo);
});
test('should preserve functions prototype if one exists', () => {
const source = {
foo: (): number => 42,
};
const bar = {};
source.foo.prototype = bar;
const name = 'foo';
// @ts-expect-error cb has any type
const replacement = cb => cb;
fill(source, name, replacement);
// But should be accessible directly
expect(source.foo.prototype).toBe(bar);
});
});
describe('extractExceptionKeysForMessage()', () => {
test('no keys', () => {
expect(extractExceptionKeysForMessage({}, 10)).toEqual('[object has no keys]');
});
test('one key should be returned as a whole if not over the length limit', () => {
expect(extractExceptionKeysForMessage({ foo: '_' }, 10)).toEqual('foo');
expect(extractExceptionKeysForMessage({ foobarbazx: '_' }, 10)).toEqual('foobarbazx');
});
test('one key should be appended with ... and truncated when over the limit', () => {
expect(extractExceptionKeysForMessage({ foobarbazqux: '_' }, 10)).toEqual('foobarbazq...');
});
test('multiple keys should be sorted and joined as a whole if not over the length limit', () => {
expect(extractExceptionKeysForMessage({ foo: '_', bar: '_' }, 10)).toEqual('bar, foo');
});
test('multiple keys should include only as much keys as can fit into the limit', () => {
expect(extractExceptionKeysForMessage({ foo: '_', bar: '_', baz: '_' }, 10)).toEqual('bar, baz');
expect(extractExceptionKeysForMessage({ footoolong: '_', verylongkey: '_', baz: '_' }, 10)).toEqual('baz');
});
test('multiple keys should truncate first key if its too long', () => {
expect(extractExceptionKeysForMessage({ barbazquxfoo: '_', baz: '_', qux: '_' }, 10)).toEqual('barbazquxf...');
});
});
/* eslint-disable deprecation/deprecation */
describe('dropUndefinedKeys()', () => {
test('simple case', () => {
expect(
dropUndefinedKeys({
a: 1,
b: undefined,
c: null,
d: 'd',
}),
).toStrictEqual({
a: 1,
c: null,
d: 'd',
});
});
test('arrays', () => {
expect(
dropUndefinedKeys({
a: [
1,
undefined,
{
a: 1,
b: undefined,
},
],
}),
).toStrictEqual({
a: [
1,
undefined,
{
a: 1,
},
],
});
});
test('nested objects', () => {
expect(
dropUndefinedKeys({
a: 1,
b: {
c: 2,
d: undefined,
e: {
f: 3,
g: undefined,
},
},
}),
).toStrictEqual({
a: 1,
b: {
c: 2,
e: {
f: 3,
},
},
});
});
describe('class instances', () => {
class MyClass {
public a = 'foo';
public b = undefined;
}
test('ignores class instance', () => {
const instance = new MyClass();
const result = dropUndefinedKeys(instance);
expect(result).toEqual({ a: 'foo', b: undefined });
expect(result).toBeInstanceOf(MyClass);
expect(Object.prototype.hasOwnProperty.call(result, 'b')).toBe(true);
});
test('ignores nested instances', () => {
const instance = new MyClass();
const result = dropUndefinedKeys({ a: [instance] });
expect(result).toEqual({ a: [instance] });
expect(result.a[0]).toBeInstanceOf(MyClass);
expect(Object.prototype.hasOwnProperty.call(result.a[0], 'b')).toBe(true);
});
});
test('should not throw on objects with circular reference', () => {
const chicken: any = {
food: undefined,
};
const egg = {
edges: undefined,
contains: chicken,
};
chicken.lays = egg;
const droppedChicken = dropUndefinedKeys(chicken);
// Removes undefined keys
expect(Object.keys(droppedChicken)).toEqual(['lays']);
expect(Object.keys(droppedChicken.lays)).toEqual(['contains']);
// Returns new object
expect(chicken === droppedChicken).toBe(false);
expect(chicken.lays === droppedChicken.lays).toBe(false);
// Returns new references within objects
expect(chicken === droppedChicken.lays.contains).toBe(false);
expect(egg === droppedChicken.lays.contains.lays).toBe(false);
// Keeps circular reference
expect(droppedChicken.lays.contains === droppedChicken).toBe(true);
});
test('arrays with circular reference', () => {
const egg: any[] = [];
const chicken = {
food: undefined,
weight: '1kg',
lays: egg,
};
egg[0] = chicken;
const droppedChicken = dropUndefinedKeys(chicken);
// Removes undefined keys
expect(Object.keys(droppedChicken)).toEqual(['weight', 'lays']);
expect(Object.keys(droppedChicken.lays)).toEqual(['0']);
// Returns new objects
expect(chicken === droppedChicken).toBe(false);
expect(egg === droppedChicken.lays).toBe(false);
// Returns new references within objects
expect(chicken === droppedChicken.lays[0]).toBe(false);
expect(egg === droppedChicken.lays[0]?.lays).toBe(false);
// Keeps circular reference
expect(droppedChicken.lays[0] === droppedChicken).toBe(true);
});
});
/* eslint-enable deprecation/deprecation */
describe('objectify()', () => {
describe('stringifies nullish values', () => {
it.each([
['undefined', undefined],
['null', null],
])('%s', (stringifiedValue, origValue): void => {
const objectifiedNullish = objectify(origValue);
expect(objectifiedNullish).toEqual(expect.any(String));
expect(objectifiedNullish.valueOf()).toEqual(stringifiedValue);
});
});
describe('wraps other primitives with their respective object wrapper classes', () => {
it.each([
['number', Number, 1121],
['string', String, 'Dogs are great!'],
['boolean', Boolean, true],
['symbol', Symbol, Symbol('Maisey')],
])('%s', (_caseName, wrapperClass, primitive) => {
const objectifiedPrimitive = objectify(primitive);
expect(objectifiedPrimitive).toEqual(expect.any(wrapperClass));
expect(objectifiedPrimitive.valueOf()).toEqual(primitive);
});
// `BigInt` doesn't exist in Node < 10, so we test it separately here.
testOnlyIfNodeVersionAtLeast(10)('bigint', () => {
// Hack to get around the fact that literal bigints cause a syntax error in older versions of Node, so the
// assignment needs to not even be parsed as code in those versions
let bigintPrimitive;
eval('bigintPrimitive = 1231n;');
const objectifiedBigInt = objectify(bigintPrimitive);
expect(objectifiedBigInt).toEqual(expect.any(BigInt));
expect(objectifiedBigInt.valueOf()).toEqual(bigintPrimitive);
});
});
it('leaves objects alone', () => {
const notAPrimitive = new Object();
const objectifiedNonPrimtive = objectify(notAPrimitive);
// `.toBe()` tests on identity, so this shows no wrapping has occurred
expect(objectifiedNonPrimtive).toBe(notAPrimitive);
});
});
describe('addNonEnumerableProperty', () => {
it('works with a plain object', () => {
const obj: { foo?: string } = {};
addNonEnumerableProperty(obj, 'foo', 'bar');
expect(obj.foo).toBe('bar');
});
it('works with a class', () => {
class MyClass {
public foo?: string;
}
const obj = new MyClass();
addNonEnumerableProperty(obj as any, 'foo', 'bar');
expect(obj.foo).toBe('bar');
});
it('works with a function', () => {
const func = vi.fn();
addNonEnumerableProperty(func as any, 'foo', 'bar');
expect((func as any).foo).toBe('bar');
func();
expect(func).toHaveBeenCalledTimes(1);
});
it('works with an existing property object', () => {
const obj = { foo: 'before' };
addNonEnumerableProperty(obj, 'foo', 'bar');
expect(obj.foo).toBe('bar');
});
it('works with an existing readonly property object', () => {
const obj = { foo: 'before' };
Object.defineProperty(obj, 'foo', {
value: 'defined',
writable: false,
});
addNonEnumerableProperty(obj, 'foo', 'bar');
expect(obj.foo).toBe('bar');
});
it('does not error with a frozen object', () => {
const obj = Object.freeze({ foo: 'before' });
addNonEnumerableProperty(obj, 'foo', 'bar');
expect(obj.foo).toBe('before');
});
});
describe('markFunctionWrapped', () => {
it('works with a function', () => {
const originalFunc = vi.fn();
const wrappedFunc = vi.fn();
markFunctionWrapped(wrappedFunc, originalFunc);
expect((wrappedFunc as WrappedFunction).__sentry_original__).toBe(originalFunc);
wrappedFunc();
expect(wrappedFunc).toHaveBeenCalledTimes(1);
expect(originalFunc).not.toHaveBeenCalled();
});
it('works with a frozen original function', () => {
const originalFunc = Object.freeze(vi.fn());
const wrappedFunc = vi.fn();
markFunctionWrapped(wrappedFunc, originalFunc);
// cannot wrap because it is frozen, but we do not error!
expect((wrappedFunc as WrappedFunction).__sentry_original__).toBe(undefined);
wrappedFunc();
expect(wrappedFunc).toHaveBeenCalledTimes(1);
expect(originalFunc).not.toHaveBeenCalled();
});
it('works with a frozen wrapped function', () => {
const originalFunc = Object.freeze(vi.fn());
const wrappedFunc = Object.freeze(vi.fn());
markFunctionWrapped(wrappedFunc, originalFunc);
// Skips adding the property, but also doesn't error
expect((wrappedFunc as WrappedFunction).__sentry_original__).toBe(undefined);
wrappedFunc();
expect(wrappedFunc).toHaveBeenCalledTimes(1);
expect(originalFunc).not.toHaveBeenCalled();
});
});