forked from trivago/prettier-plugin-sort-imports
/
get-code-from-ast.spec.ts
67 lines (61 loc) · 1.88 KB
/
get-code-from-ast.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
import { parse as babelParser } from '@babel/core';
import { ParserOptions } from '@babel/parser';
import { format } from 'prettier';
import { extractASTNodes } from '../extract-ast-nodes';
import { getCodeFromAst } from '../get-code-from-ast';
import { getExperimentalParserPlugins } from '../get-experimental-parser-plugins';
import { getImportNodes } from '../get-import-nodes';
import { getSortedNodes } from '../get-sorted-nodes';
test('it sorts imports correctly', () => {
const code = `// first comment
// second comment
import z from 'z';
import c from 'c';
import g from 'g';
import t from 't';
import k from 'k';
import a from 'a';
`;
const importNodes = getImportNodes(code);
const sortedNodes = getSortedNodes(importNodes, {
importOrder: [],
importOrderCaseInsensitive: false,
importOrderSeparation: false,
importOrderGroupNamespaceSpecifiers: false,
importOrderSortSpecifiers: false,
});
const formatted = getCodeFromAst(sortedNodes, [], code, null);
expect(format(formatted, { parser: 'babel' })).toEqual(
`// first comment
// second comment
import a from "a";
import c from "c";
import g from "g";
import k from "k";
import t from "t";
import z from "z";
`,
);
});
test('it renders directives correctly', () => {
const code = `
"use client";
// first comment
import b from 'b';
import a from 'a';`;
const parserOptions: ParserOptions = {
sourceType: 'module',
plugins: getExperimentalParserPlugins([]),
};
const ast = babelParser(code, parserOptions);
if (!ast) throw new Error('ast is null');
const { directives, importNodes } = extractASTNodes(ast);
const formatted = getCodeFromAst(importNodes, directives, code, null);
expect(format(formatted, { parser: 'babel' })).toEqual(
`"use client";
// first comment
import b from "b";
import a from "a";
`,
);
});