eslint-plugin-ava
Version:
ESLint rules for AVA
77 lines (69 loc) • 2.17 kB
JavaScript
import createAvaRule, {visitIf} from '../create-ava-rule.js';
import util from '../util.js';
const MESSAGE_ID = 'no-async-fn-without-await';
const MESSAGE_ID_SUGGESTION = 'no-async-fn-without-await-suggestion';
const create = context => {
const ava = createAvaRule(context.sourceCode);
const {sourceCode} = context;
let isTestUsed = false;
let asyncTest;
// Only count `await` directly in the test implementation, not in nested functions or in the test call itself, for example `test.skipIf(await isWindows())`
const registerUseOfAwait = node => {
if (asyncTest && sourceCode.getScope(node).variableScope.block === asyncTest) {
isTestUsed = true;
}
};
const isAsync = node => Boolean(node?.async);
return ava.merge({
CallExpression: visitIf([
ava.isInTestFile,
ava.isTestNode,
])(node => {
const implementationArgument = util.getExecutableTestImplementation(node, sourceCode);
asyncTest = isAsync(implementationArgument) && implementationArgument;
}),
AwaitExpression: registerUseOfAwait,
YieldExpression: registerUseOfAwait,
'ForOfStatement[await=true]': registerUseOfAwait,
'CallExpression:exit': visitIf([
ava.isInTestFile,
ava.isTestNode,
])(() => {
if (asyncTest && !isTestUsed) {
const asyncToken = sourceCode.getFirstToken(asyncTest, token => token.value === 'async');
context.report({
node: asyncTest,
loc: asyncToken.loc,
messageId: MESSAGE_ID,
suggest: [{
messageId: MESSAGE_ID_SUGGESTION,
fix(fixer) {
const nextToken = sourceCode.getTokenAfter(asyncToken);
return fixer.removeRange([asyncToken.range[0], nextToken.range[0]]);
},
}],
});
}
asyncTest = undefined;
isTestUsed = false;
}),
});
};
export default {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Require async tests to use `await`.',
recommended: true,
url: util.getDocsUrl(import.meta.filename),
},
hasSuggestions: true,
schema: [],
messages: {
[MESSAGE_ID]: 'Function was declared as `async` but doesn\'t use `await`.',
[MESSAGE_ID_SUGGESTION]: 'Remove the `async` keyword.',
},
languages: ['js/js'],
},
};