/
util.test.js
85 lines (78 loc) 路 2.23 KB
/
util.test.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
import { willPathCastToBoolean } from "../lib/util.js";
import { parseSync, traverse } from "@babel/core";
function getPath(input, parserOpts) {
let targetPath;
traverse(parseSync(input, { parserOpts, filename: "example.js" }), {
OptionalMemberExpression(path) {
targetPath = path;
path.stop();
},
noScope: true,
});
return targetPath;
}
describe("willPathCastToBoolean", () => {
const positiveCases = [
"if(a?.b) {}",
"while(a?.b) {}",
"a?.b ? 0 : 1",
"for(;a?.b;);",
"while(a?.b);",
"do {} while (a?.b)",
"!a?.b",
"if(a && a?.b) {}",
"if(a?.b && a) {}",
"while(a || a?.b) {}",
"while(a?.b || a) {}",
"for(; a ?? a?.b ;);",
"do {} while (0, a?.b)",
"(a?.b, 0)",
"!(a && ( b || ( c ?? ( a?.b && d ) ) ) )",
// parenthesized
"!((a?.b), 0)",
"((a?.b)) ? 0 : 1",
"while( (a || ((a?.b) && c) ) );",
];
const negativeCases = [
"() => a?.b",
"for(; a?.b ?? a;);",
"a?.b && a",
"a && a?.b",
"() => a?.b || a",
"() => a || a?.b",
"a?.b()",
"a = a?.b && null",
// parenthesized
"(a?.b)",
];
describe("default parser options", () => {
test.each(positiveCases)(
"willPathCastToBoolean(a?.b in %p) should return true",
input => {
expect(willPathCastToBoolean(getPath(input))).toBe(true);
},
);
test.each(negativeCases)(
"willPathCastToBoolean(a?.b in %p) should return false",
input => {
expect(willPathCastToBoolean(getPath(input))).toBe(false);
},
);
});
describe("createParenthesizedExpressions", () => {
test.each(positiveCases)(
"willPathCastToBoolean(a?.b in %p with { createParenthesizedExpressions: true }) should return true",
input => {
const parserOpts = { createParenthesizedExpressions: true };
expect(willPathCastToBoolean(getPath(input, parserOpts))).toBe(true);
},
);
test.each(negativeCases)(
"willPathCastToBoolean(a?.b in %p with { createParenthesizedExpressions: true }) should return false",
input => {
const parserOpts = { createParenthesizedExpressions: true };
expect(willPathCastToBoolean(getPath(input, parserOpts))).toBe(false);
},
);
});
});