/
valid-title.ts
135 lines (122 loc) · 3.46 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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 leading or trailing spaces',
},
type: 'suggestion',
schema: [
{
type: 'object',
properties: {
ignoreTypeOfDescribeName: {
type: 'boolean',
default: false,
},
},
additionalProperties: false,
},
],
fixable: 'code',
},
defaultOptions: [{ ignoreTypeOfDescribeName: false }],
create(context, [{ ignoreTypeOfDescribeName }]) {
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 &&
!(ignoreTypeOfDescribeName && isDescribe(node))
) {
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.trim().length !== title.length) {
context.report({
messageId: 'accidentalSpace',
node: argument,
fix(fixer) {
const stringValue =
argument.type === AST_NODE_TYPES.TemplateLiteral
? `\`${argument.quasis[0].value.raw}\``
: argument.raw;
return [
fixer.replaceTextRange(
argument.range,
stringValue
.replace(/^([`'"]) +?/, '$1')
.replace(/ +?([`'"])$/, '$1'),
),
];
},
});
}
const nodeName = trimFXprefix(getNodeName(node.callee));
const [firstWord] = title.split(' ');
if (firstWord.toLowerCase() === nodeName) {
context.report({
messageId: 'duplicatePrefix',
node: argument,
fix(fixer) {
const stringValue =
argument.type === AST_NODE_TYPES.TemplateLiteral
? `\`${argument.quasis[0].value.raw}\``
: argument.raw;
return [
fixer.replaceTextRange(
argument.range,
stringValue.replace(/^([`'"]).+? /, '$1'),
),
];
},
});
}
},
};
},
});