Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80552 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
// Semantic tests.
27
28
it('picks off remaining properties from an object', function() {
29
var code = transform(
30
'({ x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 });',
31
'([ x, y, z ]);'
32
);
33
expect(eval(code)).toEqual([1, 2, { a: 3, b: 4 }]);
34
});
35
36
it('picks off remaining properties from a nested object', function() {
37
var code = transform(
38
'var complex = {',
39
' x: { a: 1, b: 2, c: 3 },',
40
' y: [4, 5, 6]',
41
'};',
42
'var {',
43
' x: { a: xa, ...xbc },',
44
' y: [y0, ...y12]',
45
'} = complex;',
46
'([ xa, xbc, y0, y12 ]);'
47
);
48
expect(eval(code)).toEqual([ 1, { b: 2, c: 3 }, 4, [5, 6] ]);
49
});
50
51
it('only extracts own properties', function() {
52
var code = transform(
53
'var obj = Object.create({ x: 1 });',
54
'obj.y = 2;',
55
'({ ...y } = obj);',
56
'(y);'
57
);
58
expect(eval(code)).toEqual({ y: 2 });
59
});
60
61
it('only extracts own properties, except when they are explicit', function() {
62
var code = transform(
63
'var obj = Object.create({ x: 1, y: 2 });',
64
'obj.z = 3;',
65
'({ y, ...z } = obj);',
66
'([ y, z ]);'
67
);
68
expect(eval(code)).toEqual([ 2, { z: 3 } ]);
69
});
70
71
it('avoids passing extra properties when they are picked off', function() {
72
var code = transform(
73
'function base({ a, b, x }) { return [ a, b, x ]; }',
74
'function wrapper({ x, y, ...restConfig }) {',
75
' return base(restConfig);',
76
'}',
77
'wrapper({ x: 1, y: 2, a: 3, b: 4 });'
78
);
79
expect(eval(code)).toEqual([ 3, 4, undefined ]);
80
});
81
82
// Syntax tests.
83
84
it('throws on leading rest properties', function () {
85
expect(() => transform('({ ...x, y, z } = obj)')).toThrow();
86
});
87
88
it('throws on multiple rest properties', function () {
89
expect(() => transform('({ x, ...y, ...z } = obj)')).toThrow();
90
});
91
92
// TODO: Ideally identifier reuse should fail to transform
93
// it('throws on identifier reuse', function () {
94
// expect(() => transform('({ x: { ...z }, y: { ...z } } = obj)')).toThrow();
95
// });
96
97
});
98
99