-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathprefer-jest-mocked.ts
71 lines (60 loc) · 1.68 KB
/
prefer-jest-mocked.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
import { AST_NODE_TYPES, type TSESTree } from '@typescript-eslint/utils';
import { createRule, followTypeAssertionChain, getSourceCode } from './utils';
const mockTypes = ['Mock', 'MockedFunction', 'MockedClass', 'MockedObject'];
export default createRule({
name: __filename,
meta: {
docs: {
description: 'Prefer `jest.mocked()` over `fn as jest.Mock`',
},
messages: {
useJestMocked: 'Prefer `jest.mocked()`',
},
schema: [],
type: 'suggestion',
fixable: 'code',
},
defaultOptions: [],
create(context) {
function check(node: TSESTree.TSAsExpression | TSESTree.TSTypeAssertion) {
const { typeAnnotation } = node;
if (typeAnnotation.type !== AST_NODE_TYPES.TSTypeReference) {
return;
}
const { typeName } = typeAnnotation;
if (typeName.type !== AST_NODE_TYPES.TSQualifiedName) {
return;
}
const { left, right } = typeName;
if (
left.type !== AST_NODE_TYPES.Identifier ||
right.type !== AST_NODE_TYPES.Identifier ||
left.name !== 'jest' ||
!mockTypes.includes(right.name)
) {
return;
}
const fnName = getSourceCode(context).text.slice(
...followTypeAssertionChain(node.expression).range,
);
context.report({
node,
messageId: 'useJestMocked',
fix(fixer) {
return fixer.replaceText(node, `jest.mocked(${fnName})`);
},
});
}
return {
TSAsExpression(node) {
if (node.parent.type === AST_NODE_TYPES.TSAsExpression) {
return;
}
check(node);
},
TSTypeAssertion(node) {
check(node);
},
};
},
});