Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prefer-to-be-null TypeError with TSAsExpression #332

Closed
KaelWD opened this issue Jul 21, 2019 · 7 comments · Fixed by #403
Closed

prefer-to-be-null TypeError with TSAsExpression #332

KaelWD opened this issue Jul 21, 2019 · 7 comments · Fixed by #403

Comments

@KaelWD
Copy link

KaelWD commented Jul 21, 2019

ESLint: 6.1.0
@typescript-eslint/parser: 1.12.0
eslint-plugin-jest: 22.12.0

Code:

(expect('Model must be bound to an array if the multiple property is true') as any).toHaveBeenTipped()

Error in methodName:

TypeError: Cannot read property 'name' of undefined
Occurred while linting /home/kael/Documents/vuetifyjs/vuetify/packages/vuetify/src/components/VItemGroup/__tests__/VItemGroup.spec.ts:53
    at methodName (/home/kael/Documents/vuetifyjs/vuetify/node_modules/eslint-plugin-jest/lib/rules/util.js:70:12)
    at expectNotCase (/home/kael/Documents/vuetifyjs/vuetify/node_modules/eslint-plugin-jest/lib/rules/util.js:23:101)
    at expectToBeCase (/home/kael/Documents/vuetifyjs/vuetify/node_modules/eslint-plugin-jest/lib/rules/util.js:43:41)
    at CallExpression (/home/kael/Documents/vuetifyjs/vuetify/node_modules/eslint-plugin-jest/lib/rules/prefer-to-be-null.js:25:45)
    at /home/kael/Documents/vuetifyjs/vuetify/node_modules/eslint/lib/linter/safe-emitter.js:45:58
    at Array.forEach (<anonymous>)
    at Object.emit (/home/kael/Documents/vuetifyjs/vuetify/node_modules/eslint/lib/linter/safe-emitter.js:45:38)
    at NodeEventGenerator.applySelector (/home/kael/Documents/vuetifyjs/vuetify/node_modules/eslint/lib/linter/node-event-generator.js:253:26)
    at NodeEventGenerator.applySelectors (/home/kael/Documents/vuetifyjs/vuetify/node_modules/eslint/lib/linter/node-event-generator.js:282:22)
    at NodeEventGenerator.enterNode (/home/kael/Documents/vuetifyjs/vuetify/node_modules/eslint/lib/linter/node-event-generator.js:296:14)

image
node.parent.property is undefined

@SimenB
Copy link
Member

SimenB commented Jul 21, 2019

Thanks for the report!

This really shows how bad our current utilities are... I tried to fix this quickly, but I was unable to do so in a generic way, which means that while stopping this specific instance from crashing, other rules will probably crash in the same way as well. For now, I'd advise you to add an eslint-ignore comment, and I'll revisit this after the TS migration (#256) is complete. At that point, our helpers should be way safer and we can properly deal with this case

@G-Rath
Copy link
Collaborator

G-Rath commented Aug 4, 2019

Bamn - TS conversion fixed this.

Do we want to add a test case for this?

It's a generic problem, and in order to have a test for it we'll have to set the parser for RuleTester to RuleTester parser to be set to @typescript-eslint/parser, b/c of the as:

const ruleTester = new TSESLint.RuleTester({
  parserOptions: { ecmaVersion: 2015 },
  parser: '@typescript-eslint/parser',
});

If we want a test case, I think ideally it should be added to the "standard tests" object I'm going to look to make, in which case all tests should be run using @typescript-eslint/parser.

I've got no problem w/ this, but don't know what the impacts to performance & co might be 😂

@SimenB
Copy link
Member

SimenB commented Aug 4, 2019

Do we want to add a test case for this?

Yes :)

We can have a separate RuleTester for these ones in the same test file. I'd like to keep most tests with the default parser

@G-Rath
Copy link
Collaborator

G-Rath commented Aug 5, 2019

Here's the fix
Index: src/rules/prefer-to-be-undefined.ts
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- src/rules/prefer-to-be-undefined.ts	(revision ca5370e9d3cd7dca22e04e8754e0472466439564)
+++ src/rules/prefer-to-be-undefined.ts	(date 1564984641177)
@@ -6,6 +6,7 @@
   ParsedEqualityMatcherCall,
   ParsedExpectMatcher,
   createRule,
+  followTypeAssertionChain,
   isExpectCall,
   isParsedEqualityMatcherCall,
   parseExpectCall,
@@ -32,7 +33,7 @@
   matcher: ParsedExpectMatcher,
 ): matcher is ParsedEqualityMatcherCall<UndefinedIdentifier> =>
   isParsedEqualityMatcherCall(matcher) &&
-  isUndefinedIdentifier(matcher.arguments[0]);
+  isUndefinedIdentifier(followTypeAssertionChain(matcher.arguments[0]));
 
 export default createRule({
   name: __filename,
Index: src/rules/prefer-to-be-null.ts
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- src/rules/prefer-to-be-null.ts	(revision ca5370e9d3cd7dca22e04e8754e0472466439564)
+++ src/rules/prefer-to-be-null.ts	(date 1564984599869)
@@ -3,9 +3,11 @@
   TSESTree,
 } from '@typescript-eslint/experimental-utils';
 import {
+  MaybeTypeCast,
   ParsedEqualityMatcherCall,
   ParsedExpectMatcher,
   createRule,
+  followTypeAssertionChain,
   isExpectCall,
   isParsedEqualityMatcherCall,
   parseExpectCall,
@@ -24,12 +26,13 @@
  *
  * @param {ParsedExpectMatcher} matcher
  *
- * @return {matcher is ParsedNullEqualityMatcher}
+ * @return {matcher is ParsedEqualityMatcherCall<MaybeTypeCast<NullLiteral>>}
  */
 const isNullEqualityMatcher = (
   matcher: ParsedExpectMatcher,
-): matcher is ParsedEqualityMatcherCall<NullLiteral> =>
-  isParsedEqualityMatcherCall(matcher) && isNullLiteral(matcher.arguments[0]);
+): matcher is ParsedEqualityMatcherCall<MaybeTypeCast<NullLiteral>> =>
+  isParsedEqualityMatcherCall(matcher) &&
+  isNullLiteral(followTypeAssertionChain(matcher.arguments[0]));
 
 export default createRule({
   name: __filename,
Index: src/rules/__tests__/prefer-to-be-undefined.test.ts
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- src/rules/__tests__/prefer-to-be-undefined.test.ts	(revision ca5370e9d3cd7dca22e04e8754e0472466439564)
+++ src/rules/__tests__/prefer-to-be-undefined.test.ts	(date 1564951416912)
@@ -40,3 +40,23 @@
     },
   ],
 });
+
+new TSESLint.RuleTester({
+  parser: '@typescript-eslint/parser',
+}).run('prefer-to-be-undefined: typescript edition', rule, {
+  valid: [
+    "(expect('Model must be bound to an array if the multiple property is true') as any).toHaveBeenTipped()",
+  ],
+  invalid: [
+    {
+      code: 'expect(undefined).toBe(undefined as unknown as string as any);',
+      errors: [{ messageId: 'useToBeUndefined', column: 19, line: 1 }],
+      output: 'expect(undefined).toBeUndefined();',
+    },
+    {
+      code: 'expect("a string").not.toEqual(undefined as number);',
+      errors: [{ messageId: 'useToBeUndefined', column: 24, line: 1 }],
+      output: 'expect("a string").not.toBeUndefined();',
+    },
+  ],
+});
Index: src/rules/__tests__/prefer-to-be-null.test.ts
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- src/rules/__tests__/prefer-to-be-null.test.ts	(revision ca5370e9d3cd7dca22e04e8754e0472466439564)
+++ src/rules/__tests__/prefer-to-be-null.test.ts	(date 1564984722414)
@@ -43,3 +43,23 @@
     },
   ],
 });
+
+new TSESLint.RuleTester({
+  parser: '@typescript-eslint/parser',
+}).run('prefer-to-be-null: typescript edition', rule, {
+  valid: [
+    "(expect('Model must be bound to an array if the multiple property is true') as any).toHaveBeenTipped()",
+  ],
+  invalid: [
+    {
+      code: 'expect(null).toBe(null as unknown as string as unknown as any);',
+      errors: [{ messageId: 'useToBeNull', column: 14, line: 1 }],
+      output: 'expect(null).toBeNull();',
+    },
+    {
+      code: 'expect("a string").not.toEqual(null as number);',
+      errors: [{ messageId: 'useToBeNull', column: 24, line: 1 }],
+      output: 'expect("a string").not.toBeNull();',
+    },
+  ],
+});
Index: src/rules/utils.ts
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- src/rules/utils.ts	(revision ca5370e9d3cd7dca22e04e8754e0472466439564)
+++ src/rules/utils.ts	(date 1564984544619)
@@ -14,6 +14,35 @@
   return `${REPO_URL}/blob/v${version}/docs/rules/${ruleName}.md`;
 });
 
+export type MaybeTypeCast<Expression extends TSESTree.Expression> =
+  | TSTypeCastExpression<Expression>
+  | Expression;
+
+export type TSTypeCastExpression<
+  Expression extends TSESTree.Expression = TSESTree.Expression
+> = AsExpressionChain<Expression> | TypeAssertionChain<Expression>;
+
+interface AsExpressionChain<
+  Expression extends TSESTree.Expression = TSESTree.Expression
+> extends TSESTree.TSAsExpression {
+  expression: AsExpressionChain<Expression> | Expression;
+}
+
+interface TypeAssertionChain<
+  Expression extends TSESTree.Expression = TSESTree.Expression
+> extends TSESTree.TSTypeAssertion {
+  // expression: TypeAssertionChain<Expression> | Expression;
+  expression: any; // https://github.com/typescript-eslint/typescript-eslint/issues/802
+}
+
+export const followTypeAssertionChain = (
+  expression: TSESTree.Expression | TSTypeCastExpression,
+): TSESTree.Expression =>
+  expression.type === AST_NODE_TYPES.TSAsExpression ||
+  expression.type === AST_NODE_TYPES.TSTypeAssertion
+    ? followTypeAssertionChain(expression.expression)
+    : expression;
+
 /**
  * A `Literal` with a `value` of type `string`.
  */

I'll make a PR once #363 is merged

The takeaway is that:

  • Casts are to expression nodes as MemberExpressions are to expect() CallExpections: they make a chain leading down to the actual value that's being cast,
  • When working w/ arguments (among other things) we should consider what if they're being cast
    • Typically rules that are working on argument raw values such as prefer-to-be-undefined & prefer-to-be-null we should ignore the cast in favor of whatever the actual value is.
  • followTypeAssertionChain will return the final node in the cast chain, and should be usable for most general cases w/o worry.

This raises the question of what to do w/ prefer-to-contain, as it checks for a boolean literal.
I think for consistency it should probably also use followTypeAssertionChain, b/c why would you cast a boolean type anyway...?

@SimenB
Copy link
Member

SimenB commented Aug 21, 2019

@G-Rath can we fix this now?

@G-Rath
Copy link
Collaborator

G-Rath commented Aug 21, 2019

@SimenB Sure can! #403 has got your back.

Sorry for the delay - a few things popped up that stole my attention, combined w/ tackling no-untrimmed-title 😬

@G-Rath G-Rath self-assigned this Aug 21, 2019
@SimenB
Copy link
Member

SimenB commented Aug 21, 2019

🎉 This issue has been resolved in version 22.15.2 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants