-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathprefer-lowercase-title.ts
120 lines (108 loc) · 3.18 KB
/
prefer-lowercase-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
import { AST } from 'eslint'
import ESTree from 'estree'
import { getStringValue, isStringNode } from '../utils/ast.js'
import { createRule } from '../utils/createRule.js'
import { isTypeOfFnCall, parseFnCall } from '../utils/parseFnCall.js'
type Method = 'test' | 'test.describe'
export default createRule({
create(context) {
const { allowedPrefixes, ignore, ignoreTopLevelDescribe } = {
allowedPrefixes: [] as string[],
ignore: [] as Method[],
ignoreTopLevelDescribe: false,
...((context.options?.[0] as Record<string, unknown>) ?? {}),
}
let describeCount = 0
return {
CallExpression(node) {
const call = parseFnCall(context, node)
if (call?.type !== 'describe' && call?.type !== 'test') {
return
}
if (call.type === 'describe') {
describeCount++
if (ignoreTopLevelDescribe && describeCount === 1) {
return
}
}
const [title] = node.arguments
if (!isStringNode(title)) {
return
}
const description = getStringValue(title)
if (
!description ||
allowedPrefixes.some((name) => description.startsWith(name))
) {
return
}
const method = call.type === 'describe' ? 'test.describe' : 'test'
const firstCharacter = description.charAt(0)
if (
!firstCharacter ||
firstCharacter === firstCharacter.toLowerCase() ||
ignore.includes(method)
) {
return
}
context.report({
data: { method },
fix(fixer) {
const rangeIgnoringQuotes: AST.Range = [
title.range![0] + 1,
title.range![1] - 1,
]
const newDescription =
description.substring(0, 1).toLowerCase() +
description.substring(1)
return fixer.replaceTextRange(rangeIgnoringQuotes, newDescription)
},
messageId: 'unexpectedLowercase',
node: node.arguments[0],
})
},
'CallExpression:exit'(node: ESTree.CallExpression) {
if (isTypeOfFnCall(context, node, ['describe'])) {
describeCount--
}
},
}
},
meta: {
docs: {
category: 'Best Practices',
description: 'Enforce lowercase test names',
recommended: false,
url: 'https://github.com/playwright-community/eslint-plugin-playwright/tree/main/docs/rules/prefer-lowercase-title.md',
},
fixable: 'code',
messages: {
unexpectedLowercase: '`{{method}}`s should begin with lowercase',
},
schema: [
{
additionalProperties: false,
properties: {
allowedPrefixes: {
additionalItems: false,
items: { type: 'string' },
type: 'array',
},
ignore: {
additionalItems: false,
items: {
enum: ['test.describe', 'test'],
},
type: 'array',
},
ignoreTopLevelDescribe: {
default: false,
type: 'boolean',
},
},
type: 'object',
},
],
type: 'suggestion',
},
})