/
codegen.spec.ts
86 lines (73 loc) · 2.48 KB
/
codegen.spec.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
import {JsonExpressionCodegen} from '../codegen';
import {Expr} from '../types';
const check = (expression: Expr, expected: unknown, data: unknown = null) => {
const codegen = new JsonExpressionCodegen({
expression,
});
const fn = codegen.run().compile();
// console.log(codegen.generate().js);
// console.log(fn.toString());
const result = fn({data});
expect(result).toStrictEqual(expected);
};
describe('get', () => {
test('can pick from object', () => {
check(['get', '/foo'], 'bar', {foo: 'bar'});
check(['=', '/foo'], 'bar', {foo: 'bar'});
check(['=', '/baz'], undefined, {foo: 'bar'});
});
test('can pick using expression', () => {
check(['get', ['get', '/pointer']], 'bar', {foo: 'bar', pointer: '/foo'});
});
test('can pick itself recursively', () => {
check(['=', ['=', '/pointer']], '/pointer', {foo: 'bar', pointer: '/pointer'});
});
});
describe('eq', () => {
test('on two literals', () => {
check(['==', 1, 2], false);
check(['==', {foo: 'bar'}, {foo: 'bar'}], true);
check(['==', {foo: 'bar'}, {foo: 'baz'}], false);
check(['==', [[]], [[]]], true);
});
test('literal and expression', () => {
check(['eq', 3, ['=', '/foo']], false);
check(['eq', 'bar', ['eq', 1, 1]], false);
check(['eq', true, ['eq', 1, 1]], true);
});
test('together with get', () => {
check(['eq', 3, ['=', '/foo']], true, {foo: 3});
});
});
describe('ne', () => {
test('on two literals', () => {
check(['!=', 1, 2], true);
check(['!=', {foo: 'bar'}, {foo: 'bar'}], false);
check(['!=', {foo: 'bar'}, {foo: 'baz'}], true);
check(['!=', [[]], [[]]], false);
});
test('literal and expression', () => {
check(['ne', 3, ['=', '/foo']], true);
check(['ne', 'bar', ['eq', 1, 1]], true);
check(['!=', true, ['eq', 1, 1]], false);
});
test('together with get', () => {
check(['ne', 3, ['=', '/foo']], false, {foo: 3});
});
});
describe('not', () => {
test('on two literals', () => {
check(['!', ['==', 1, 2]], true);
check(['!', ['==', {foo: 'bar'}, {foo: 'bar'}]], false);
check(['not', ['==', {foo: 'bar'}, {foo: 'baz'}]], true);
check(['not', ['==', [[]], [[]]]], false);
});
test('literal and expression', () => {
check(['!', ['eq', 3, ['=', '/foo']]], true);
check(['not', ['eq', 'bar', ['eq', 1, 1]]], true);
check(['not', ['eq', true, ['eq', 1, 1]]], false);
});
test('together with get', () => {
check(['!', ['eq', 3, ['=', '/foo']]], false, {foo: 3});
});
});