|
1 | 1 | import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils';
|
2 |
| -import { getDocsUrl, ALL_QUERIES_METHODS } from '../utils'; |
3 |
| -import { isMemberExpression } from '../node-utils'; |
| 2 | +import { |
| 3 | + getDocsUrl, |
| 4 | + ALL_QUERIES_METHODS, |
| 5 | + PRESENCE_MATCHERS, |
| 6 | + ABSENCE_MATCHERS, |
| 7 | +} from '../utils'; |
| 8 | +import { |
| 9 | + findClosestCallNode, |
| 10 | + isIdentifier, |
| 11 | + isMemberExpression, |
| 12 | +} from '../node-utils'; |
4 | 13 |
|
5 | 14 | export const RULE_NAME = 'prefer-explicit-assert';
|
6 | 15 | export type MessageIds =
|
@@ -48,6 +57,7 @@ export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({
|
48 | 57 | properties: {
|
49 | 58 | assertion: {
|
50 | 59 | type: 'string',
|
| 60 | + enum: PRESENCE_MATCHERS, |
51 | 61 | },
|
52 | 62 | customQueryNames: {
|
53 | 63 | type: 'array',
|
@@ -84,15 +94,29 @@ export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({
|
84 | 94 | messageId: 'preferExplicitAssert',
|
85 | 95 | });
|
86 | 96 | } else if (assertion) {
|
87 |
| - const expectation = node.parent.parent.parent; |
| 97 | + const expectCallNode = findClosestCallNode(node, 'expect'); |
| 98 | + |
| 99 | + const expectStatement = expectCallNode.parent as TSESTree.MemberExpression; |
| 100 | + const property = expectStatement.property as TSESTree.Identifier; |
| 101 | + let matcher = property.name; |
| 102 | + let isNegatedMatcher = false; |
88 | 103 |
|
89 | 104 | if (
|
90 |
| - expectation.type === 'MemberExpression' && |
91 |
| - expectation.property.type === 'Identifier' && |
92 |
| - expectation.property.name !== assertion |
| 105 | + matcher === 'not' && |
| 106 | + isMemberExpression(expectStatement.parent) && |
| 107 | + isIdentifier(expectStatement.parent.property) |
93 | 108 | ) {
|
| 109 | + isNegatedMatcher = true; |
| 110 | + matcher = expectStatement.parent.property.name; |
| 111 | + } |
| 112 | + |
| 113 | + const shouldEnforceAssertion = |
| 114 | + (!isNegatedMatcher && PRESENCE_MATCHERS.includes(matcher)) || |
| 115 | + (isNegatedMatcher && ABSENCE_MATCHERS.includes(matcher)); |
| 116 | + |
| 117 | + if (shouldEnforceAssertion && matcher !== assertion) { |
94 | 118 | context.report({
|
95 |
| - node: expectation.property, |
| 119 | + node: property, |
96 | 120 | messageId: 'preferExplicitAssertAssertion',
|
97 | 121 | data: {
|
98 | 122 | assertion,
|
|
0 commit comments