Skip to content

Commit

Permalink
chore(no-test-callback): migrate to TS (#321)
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Rath authored and SimenB committed Jul 22, 2019
1 parent ccbe766 commit d0a8428
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 11 deletions.
@@ -1,7 +1,7 @@
import { RuleTester } from 'eslint';
import { TSESLint } from '@typescript-eslint/experimental-utils';
import rule from '../no-test-callback';

const ruleTester = new RuleTester({
const ruleTester = new TSESLint.RuleTester({
parserOptions: {
ecmaVersion: 8,
},
Expand Down
43 changes: 34 additions & 9 deletions src/rules/no-test-callback.js → src/rules/no-test-callback.ts
@@ -1,16 +1,21 @@
import { getDocsUrl, isTestCase } from './util';
import { createRule, isFunction, isTestCase } from './tsUtils';

export default {
export default createRule({
name: __filename,
meta: {
docs: {
url: getDocsUrl(__filename),
category: 'Best Practices',
description: 'Avoid using a callback in asynchronous tests',
recommended: false,
},
messages: {
illegalTestCallback: 'Illegal usage of test callback',
},
fixable: 'code',
schema: [],
type: 'suggestion',
},
defaultOptions: [],
create(context) {
return {
CallExpression(node) {
Expand All @@ -20,24 +25,44 @@ export default {

const [, callback] = node.arguments;

if (
!/^(Arrow)?FunctionExpression$/.test(callback.type) ||
callback.params.length !== 1
) {
if (!isFunction(callback) || callback.params.length !== 1) {
return;
}

const [argument] = callback.params;

context.report({
node: argument,
messageId: 'illegalTestCallback',
fix(fixer) {
const sourceCode = context.getSourceCode();
const { body } = callback;

/* istanbul ignore if */
if (!body) {
throw new Error(
`Unexpected null when attempting to fix ${context.getFilename()} - please file a github issue at https://github.com/jest-community/eslint-plugin-jest`,
);
}

const sourceCode = context.getSourceCode();
const firstBodyToken = sourceCode.getFirstToken(body);
const lastBodyToken = sourceCode.getLastToken(body);
const tokenBeforeArgument = sourceCode.getTokenBefore(argument);
const tokenAfterArgument = sourceCode.getTokenAfter(argument);

/* istanbul ignore if */
if (
!('name' in argument) ||
!firstBodyToken ||
!lastBodyToken ||
!tokenBeforeArgument ||
!tokenAfterArgument
) {
throw new Error(
`Unexpected null when attempting to fix ${context.getFilename()} - please file a github issue at https://github.com/jest-community/eslint-plugin-jest`,
);
}

const argumentInParens =
tokenBeforeArgument.value === '(' &&
tokenAfterArgument.value === ')';
Expand Down Expand Up @@ -78,4 +103,4 @@ export default {
},
};
},
};
});

0 comments on commit d0a8428

Please sign in to comment.