-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
ast.js
104 lines (81 loc) · 2.2 KB
/
ast.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
'use strict';
const assert = require('assert');
const sinon = require('sinon');
const espree = require('espree');
const ast = require('../../lib/util/ast');
const traverseReturns = ast.traverseReturns;
const DEFAULT_CONFIG = {
ecmaVersion: 6
};
const parseCode = (code) => {
const ASTnode = espree.parse(code, DEFAULT_CONFIG);
// Return only first statement
return ASTnode.body[0];
};
const mockContext = {};
describe('ast', () => {
describe('traverseReturnStatements', () => {
it('Correctly traverses function declarations', () => {
const spy = sinon.spy();
traverseReturns(parseCode(`
function foo({prop}) {
return;
}
`), mockContext, spy);
assert(spy.calledOnce);
});
it('Correctly traverses function expressions', () => {
const spy = sinon.spy();
traverseReturns(parseCode(`
const foo = function({prop}) {
return;
}
`).declarations[0].init, mockContext, spy);
assert(spy.calledOnce);
});
it('Correctly traverses arrow functions', () => {
const spy = sinon.spy();
traverseReturns(parseCode(`
({prop}) => {
return;
}
`).expression, mockContext, spy);
assert(spy.calledOnce);
spy.resetHistory();
traverseReturns(parseCode(`
({prop}) => 'someething'
`).expression, mockContext, spy);
assert(spy.calledOnce);
});
it('Correctly traverses inside control flow expressions', () => {
const spy = sinon.spy();
traverseReturns(parseCode(`
function foo({prop}) {
if (prop) {
return 0;
} else {
return 1;
}
while(prop) {
return 2;
}
for (;;) {
return 3;
}
switch (prop) {
case 'a':
return 4;
default:
return 5;
}
const foo = () => 'not valid';
}
`), mockContext, spy);
const enterCalls = spy.getCalls();
assert.strictEqual(enterCalls.length, 6);
enterCalls.forEach((node, idx) => {
assert.strictEqual(node.lastArg.argument.value, idx);
});
});
});
});