Debian Codegraph @

charcodes/packages/babel-plugin-transform-charcodes/test/transformation.test.js

raw
1 import { parse } from '@babel/parser';
2 import * as types from '@babel/types';
3 import generate from '@babel/generator';
4 import traverse from '@babel/traverse';
5
6 import visitor from '../src';
7
8 function transform(code) {
9 const ast = parse(code, {
10 sourceType: 'module',
11 });
12
13 traverse(ast, visitor({ types }).visitor, null, {});
14
15 return generate(ast).code;
16 }
17
18 function assertOutput(code, expected) {
19 const out = transform(code);
20
21 expect(out).toEqual(expected);
22 }
23
24 describe('function', () => {
25
26 it('should hoist a function and call it', () => {
27
28 const out = transform(`
29 import * as charcodes from "charcodes"
30
31 (charcodes.isDigit(1))
32 `)
33
34 const expected = `
35 var _isDigit = function isDigit(code) {
36 return code >= 48 && code <= 57;
37 };
38 _isDigit(1);
39 `
40
41 assertOutput(expected, out)
42 })
43
44 })
45
46 describe('constant', () => {
47
48 it('should inline a constant', () => {
49
50 const out = transform(`
51 import * as charcodes from "charcodes"
52
53 charcodes.space
54 `)
55
56 const expected = `
57 32
58 `
59
60 assertOutput(expected, out)
61 })
62
63 it('should throw if the key is unknown', () => {
64
65 const fn = () => transform(`
66 import * as charcodes from "charcodes"
67
68 charcodes.somethinglikefoobar
69 `)
70
71 expect(fn).toThrow(/unknown key/);
72 })
73
74 })