-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
typeFlagUtils.test.ts
94 lines (83 loc) · 2.86 KB
/
typeFlagUtils.test.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
87
88
89
90
91
92
93
94
import { parseForESLint } from '@typescript-eslint/parser';
import type { TSESTree } from '@typescript-eslint/typescript-estree';
import path from 'path';
import * as ts from 'typescript';
import { getTypeFlags, isTypeFlagSet } from '../src';
import { expectToHaveParserServices } from './test-utils/expectToHaveParserServices';
describe('typeFlagUtils', () => {
const rootDir = path.join(__dirname, 'fixtures');
function getType(code: string): ts.Type {
const { ast, services } = parseForESLint(code, {
project: './tsconfig.json',
filePath: path.join(rootDir, 'file.ts'),
tsconfigRootDir: rootDir,
});
expectToHaveParserServices(services);
const declaration = ast.body[0] as TSESTree.TSTypeAliasDeclaration;
return services.getTypeAtLocation(declaration.id);
}
describe('getTypeFlags', () => {
function runTestForAliasDeclaration(
code: string,
expected: ts.TypeFlags,
): void {
const type = getType(code);
const result = getTypeFlags(type);
expect(result).toBe(expected);
}
it.each([
['type Test = any;', 1],
['type Test = unknown;', 2],
['type Test = string;', 4],
['type Test = number;', 8],
['type Test = "text";', 128],
['type Test = 123;', 256],
['type Test = string | number', 12],
['type Test = "text" | 123', 384],
])('when code is "%s", type flags is %d', runTestForAliasDeclaration);
});
describe('isTypeFlagSet', () => {
function runTestForAliasDeclaration(
code: string,
flagsToCheck: ts.TypeFlags,
expected: boolean,
): void {
const type = getType(code);
const result = isTypeFlagSet(type, flagsToCheck);
expect(result).toBe(expected);
}
describe('is type flags set', () => {
function runTestIsTypeFlagSet(
code: string,
flagsToCheck: ts.TypeFlags,
): void {
runTestForAliasDeclaration(code, flagsToCheck, true);
}
it.each([
['type Test = any;', ts.TypeFlags.Any],
['type Test = string;', ts.TypeFlags.String],
['type Test = string | number;', ts.TypeFlags.String],
['type Test = string & { foo: string };', ts.TypeFlags.Intersection],
])(
'when code is "%s" and flagsToCheck is %d , returns true',
runTestIsTypeFlagSet,
);
});
describe('is not type flags set', () => {
function runTestIsNotTypeFlagSet(
code: string,
flagsToCheck: ts.TypeFlags,
): void {
runTestForAliasDeclaration(code, flagsToCheck, false);
}
it.each([
['type Test = string', ts.TypeFlags.Any],
['type Test = string | number;', ts.TypeFlags.Any],
['type Test = string & { foo: string }', ts.TypeFlags.String],
])(
'when code is "%s" and flagsToCheck is %d , returns false',
runTestIsNotTypeFlagSet,
);
});
});
});