eslint-plugin-jest-extended
Version:
Eslint rules for Jest Extended
72 lines (70 loc) • 3.09 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _utils = require("@typescript-eslint/utils");
var _utils2 = require("./utils");
const isArrayIsArrayCall = node => node.type === _utils.AST_NODE_TYPES.CallExpression && node.callee.type === _utils.AST_NODE_TYPES.MemberExpression && (0, _utils2.isSupportedAccessor)(node.callee.object, 'Array') && (0, _utils2.isSupportedAccessor)(node.callee.property, 'isArray');
var _default = exports.default = (0, _utils2.createRule)({
name: __filename,
meta: {
docs: {
description: 'Suggest using `toBeArray()`'
},
messages: {
preferToBeArray: 'Prefer using `toBeArray()` to test if a value is an array.'
},
fixable: 'code',
type: 'suggestion',
schema: []
},
defaultOptions: [],
create(context) {
return {
CallExpression(node) {
const jestFnCall = (0, _utils2.parseJestFnCall)(node, context);
if (jestFnCall?.type !== 'expect') {
return;
}
if ((0, _utils2.isParsedInstanceOfMatcherCall)(jestFnCall, 'Array')) {
context.report({
node: jestFnCall.matcher,
messageId: 'preferToBeArray',
fix: fixer => [fixer.replaceTextRange([jestFnCall.matcher.range[0], jestFnCall.matcher.range[1] + '(Array)'.length], 'toBeArray()')]
});
return;
}
const {
parent: expect
} = jestFnCall.head.node;
if (expect?.type !== _utils.AST_NODE_TYPES.CallExpression) {
return;
}
const [expectArg] = expect.arguments;
if (!expectArg || !(0, _utils2.isBooleanEqualityMatcher)(jestFnCall) || !(isArrayIsArrayCall(expectArg) || (0, _utils2.isInstanceOfBinaryExpression)(expectArg, 'Array'))) {
return;
}
context.report({
node: jestFnCall.matcher,
messageId: 'preferToBeArray',
fix(fixer) {
const fixes = [fixer.replaceText(jestFnCall.matcher, 'toBeArray'), expectArg.type === _utils.AST_NODE_TYPES.CallExpression ? fixer.remove(expectArg.callee) : fixer.removeRange([expectArg.left.range[1], expectArg.range[1]])];
let invertCondition = (0, _utils2.getAccessorValue)(jestFnCall.matcher) === 'toBeFalse';
if (jestFnCall.args.length) {
const [matcherArg] = jestFnCall.args;
fixes.push(fixer.remove(matcherArg));
// toBeFalse can't have arguments, so this won't be true beforehand
invertCondition = matcherArg.type === _utils.AST_NODE_TYPES.Literal && (0, _utils2.followTypeAssertionChain)(matcherArg).value === false;
}
if (invertCondition) {
const notModifier = jestFnCall.modifiers.find(nod => (0, _utils2.getAccessorValue)(nod) === 'not');
fixes.push(notModifier ? fixer.removeRange([notModifier.range[0] - 1, notModifier.range[1]]) : fixer.insertTextBefore(jestFnCall.matcher, 'not.'));
}
return fixes;
}
});
}
};
}
});
;