/
valid-title.ts
92 lines (81 loc) · 2.15 KB
/
valid-title.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
import {
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import {
DescribeAlias,
TestCaseName,
createRule,
getNodeName,
getStringValue,
isDescribe,
isStringNode,
isTestCase,
} from './utils';
const trimFXprefix = (word: string) =>
['f', 'x'].includes(word.charAt(0)) ? word.substr(1) : word;
export default createRule({
name: __filename,
meta: {
docs: {
category: 'Best Practices',
description: 'Enforce valid titles',
recommended: false,
},
messages: {
titleMustBeString: 'Title must be a string',
emptyTitle: '{{ jestFunctionName }} should not have an empty title',
duplicatePrefix: 'should not have duplicate prefix',
accidentalSpace: 'should not have space in the beginning',
},
type: 'suggestion',
schema: [],
},
defaultOptions: [],
create(context) {
return {
CallExpression(node: TSESTree.CallExpression) {
if (!(isDescribe(node) || isTestCase(node)) || !node.arguments.length) {
return;
}
const [argument] = node.arguments;
if (!isStringNode(argument)) {
if (argument.type !== AST_NODE_TYPES.TemplateLiteral) {
context.report({
messageId: 'titleMustBeString',
loc: argument.loc,
});
}
return;
}
const title = getStringValue(argument);
if (!title) {
context.report({
messageId: 'emptyTitle',
data: {
jestFunctionName: isDescribe(node)
? DescribeAlias.describe
: TestCaseName.test,
},
node,
});
return;
}
if (title.trimLeft().length !== title.length) {
context.report({
messageId: 'accidentalSpace',
node,
});
}
const nodeName = trimFXprefix(getNodeName(node.callee));
const [firstWord] = title.split(' ');
if (firstWord.toLowerCase() === nodeName) {
context.report({
messageId: 'duplicatePrefix',
node,
});
}
},
};
},
});