Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
81153 views
1
/**
2
* @emails [email protected]
3
*/
4
5
/*jshint evil:true*/
6
7
require('mock-modules').autoMockOff();
8
9
describe('es7-rest-property-visitors', function() {
10
var transformFn;
11
12
var visitors;
13
14
beforeEach(function() {
15
require('mock-modules').dumpCache();
16
transformFn = require('../../src/jstransform').transform;
17
18
visitors = require('../es6-destructuring-visitors').visitorList;
19
});
20
21
function transform(code) {
22
var lines = Array.prototype.join.call(arguments, '\n');
23
return transformFn(visitors, lines).code;
24
}
25
26
function expectTransform(code, result) {
27
expect(transform(code)).toEqual(result);
28
}
29
30
// Semantic tests.
31
32
it('picks off remaining properties from an object', function() {
33
var code = transform(
34
'({ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 });',
35
'([ x, y, z ]);'
36
);
37
expect(eval(code)).toEqual([1, 2, { a: 3, b: 4 }]);
38
});
39
40
it('picks off remaining properties from a nested object', function() {
41
var code = transform(
42
'var complex = {',
43
' x: { a: 1, b: 2, c: 3 },',
44
' y: [4, 5, 6]',
45
'};',
46
'var {',
47
' x: { a: xa, ...xbc },',
48
' y: [y0, ...y12]',
49
'} = complex;',
50
'([ xa, xbc, y0, y12 ]);'
51
);
52
expect(eval(code)).toEqual([ 1, { b: 2, c: 3 }, 4, [5, 6] ]);
53
});
54
55
it('only extracts own properties', function() {
56
var code = transform(
57
'var obj = Object.create({ x: 1 });',
58
'obj.y = 2;',
59
'({ ...y } = obj);',
60
'(y);'
61
);
62
expect(eval(code)).toEqual({ y: 2 });
63
});
64
65
it('only extracts own properties, except when they are explicit', function() {
66
var code = transform(
67
'var obj = Object.create({ x: 1, y: 2 });',
68
'obj.z = 3;',
69
'({ y, ...z } = obj);',
70
'([ y, z ]);'
71
);
72
expect(eval(code)).toEqual([ 2, { z: 3 } ]);
73
});
74
75
it('avoids passing extra properties when they are picked off', function() {
76
var code = transform(
77
'function base({ a, b, x }) { return [ a, b, x ]; }',
78
'function wrapper({ x, y, ...restConfig }) {',
79
' return base(restConfig);',
80
'}',
81
'wrapper({ x: 1, y: 2, a: 3, b: 4 });'
82
);
83
expect(eval(code)).toEqual([ 3, 4, undefined ]);
84
});
85
86
// Syntax tests.
87
88
it('throws on leading rest properties', function () {
89
expect(() => transform('({ ...x, y, z } = obj)')).toThrow();
90
});
91
92
it('throws on multiple rest properties', function () {
93
expect(() => transform('({ x, ...y, ...z } = obj)')).toThrow();
94
});
95
96
// TODO: Ideally identifier reuse should fail to transform
97
// it('throws on identifier reuse', function () {
98
// expect(() => transform('({ x: { ...z }, y: { ...z } } = obj)')).toThrow();
99
// });
100
101
});
102
103