Skip to content

Commit

Permalink
chore(prefer-to-be-undefined): convert to typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Rath committed Aug 15, 2019
1 parent c914f1b commit 8ed5547
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 56 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { RuleTester } from 'eslint';
import { TSESLint } from '@typescript-eslint/experimental-utils';
import rule from '../prefer-to-be-undefined';

const ruleTester = new RuleTester();
const ruleTester = new TSESLint.RuleTester();

ruleTester.run('prefer-to-be-undefined', rule, {
valid: [
'expect(undefined).toBeUndefined();',
'expect(true).not.toBeUndefined();',
'expect({}).toEqual({});',
'expect(null).toEqual(null);',
'expect(something).toBe()',
'expect(something).toBe(somethingElse)',
'expect(something).toEqual(somethingElse)',
'expect(something).not.toBe(somethingElse)',
Expand Down
54 changes: 0 additions & 54 deletions src/rules/prefer-to-be-undefined.js

This file was deleted.

75 changes: 75 additions & 0 deletions src/rules/prefer-to-be-undefined.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import {
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import {
ParsedEqualityMatcherCall,
ParsedExpectMatcher,
createRule,
isExpectCall,
isParsedEqualityMatcherCall,
parseExpectCall,
} from './tsUtils';

interface UndefinedIdentifier extends TSESTree.Identifier {
name: 'undefined';
}

const isUndefinedIdentifier = (
node: TSESTree.Node,
): node is UndefinedIdentifier =>
node.type === AST_NODE_TYPES.Identifier && node.name === `${undefined}`;

/**
* Checks if the given `ParsedExpectMatcher` is a call to one of the equality matchers,
* with a `undefined` identifier as the sole argument.
*
* @param {ParsedExpectMatcher} matcher
*
* @return {matcher is ParsedEqualityMatcherCall<UndefinedIdentifier>}
*/
const isUndefinedEqualityMatcher = (
matcher: ParsedExpectMatcher,
): matcher is ParsedEqualityMatcherCall<UndefinedIdentifier> =>
isParsedEqualityMatcherCall(matcher) &&
isUndefinedIdentifier(matcher.arguments[0]);

export default createRule({
name: __filename,
meta: {
docs: {
category: 'Best Practices',
description: 'Suggest using `toBeUndefined()`',
recommended: false,
},
messages: {
useToBeUndefined: 'Use toBeUndefined() instead',
},
fixable: 'code',
type: 'suggestion',
schema: [],
},
defaultOptions: [],
create(context) {
return {
CallExpression(node) {
if (!isExpectCall(node)) {
return;
}

const { matcher } = parseExpectCall(node);

if (matcher && isUndefinedEqualityMatcher(matcher)) {
context.report({
fix: fixer => [
fixer.replaceText(matcher.node.property, 'toBeUndefined'),
fixer.remove(matcher.arguments[0]),
],
messageId: 'useToBeUndefined',
node: matcher.node.property,
});
}
},
};
},
});

0 comments on commit 8ed5547

Please sign in to comment.