|
1 |
| -import { AST_NODE_TYPES, TSESTree } from '@typescript-eslint/utils'; |
| 1 | +import { AST_NODE_TYPES, TSESLint, TSESTree } from '@typescript-eslint/utils'; |
2 | 2 | import { createRule, getNodeName } from './utils';
|
3 | 3 |
|
4 | 4 | const findNodeObject = (
|
@@ -39,6 +39,27 @@ const getJestFnCall = (node: TSESTree.Node): TSESTree.CallExpression | null => {
|
39 | 39 | return getJestFnCall(obj);
|
40 | 40 | };
|
41 | 41 |
|
| 42 | +const getAutoFixMockImplementation = ( |
| 43 | + jestFnCall: TSESTree.CallExpression, |
| 44 | + context: TSESLint.RuleContext<'useJestSpyOn', unknown[]>, |
| 45 | +): string => { |
| 46 | + const hasMockImplementationAlready = |
| 47 | + jestFnCall.parent?.type === AST_NODE_TYPES.MemberExpression && |
| 48 | + jestFnCall.parent.property.type === AST_NODE_TYPES.Identifier && |
| 49 | + jestFnCall.parent.property.name === 'mockImplementation'; |
| 50 | + |
| 51 | + if (hasMockImplementationAlready) { |
| 52 | + return ''; |
| 53 | + } |
| 54 | + |
| 55 | + const [arg] = jestFnCall.arguments; |
| 56 | + const argSource = arg && context.getSourceCode().getText(arg); |
| 57 | + |
| 58 | + return argSource |
| 59 | + ? `.mockImplementation(${argSource})` |
| 60 | + : '.mockImplementation()'; |
| 61 | +}; |
| 62 | + |
42 | 63 | export default createRule({
|
43 | 64 | name: __filename,
|
44 | 65 | meta: {
|
@@ -71,12 +92,13 @@ export default createRule({
|
71 | 92 | messageId: 'useJestSpyOn',
|
72 | 93 | fix(fixer) {
|
73 | 94 | const leftPropQuote =
|
74 |
| - left.property.type === AST_NODE_TYPES.Identifier ? "'" : ''; |
75 |
| - const [arg] = jestFnCall.arguments; |
76 |
| - const argSource = arg && context.getSourceCode().getText(arg); |
77 |
| - const mockImplementation = argSource |
78 |
| - ? `.mockImplementation(${argSource})` |
79 |
| - : '.mockImplementation()'; |
| 95 | + left.property.type === AST_NODE_TYPES.Identifier && !left.computed |
| 96 | + ? "'" |
| 97 | + : ''; |
| 98 | + const mockImplementation = getAutoFixMockImplementation( |
| 99 | + jestFnCall, |
| 100 | + context, |
| 101 | + ); |
80 | 102 |
|
81 | 103 | return [
|
82 | 104 | fixer.insertTextBefore(left, `jest.spyOn(`),
|
|
0 commit comments