eslint-plugin-testing-library
Version:
ESLint plugin to follow best practices and anticipate common mistakes when writing tests with Testing Library
83 lines (82 loc) • 2.85 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RULE_NAME = void 0;
const utils_1 = require("@typescript-eslint/utils");
const create_testing_library_rule_1 = require("../create-testing-library-rule");
const utils_2 = require("../utils");
exports.RULE_NAME = 'no-node-access';
const ALL_PROHIBITED_MEMBERS = [
...utils_2.ALL_RETURNING_NODES,
...utils_2.EVENT_HANDLER_METHODS,
];
exports.default = (0, create_testing_library_rule_1.createTestingLibraryRule)({
name: exports.RULE_NAME,
meta: {
type: 'problem',
docs: {
description: 'Disallow direct Node access',
recommendedConfig: {
dom: 'error',
angular: 'error',
react: 'error',
vue: 'error',
svelte: 'error',
marko: 'error',
},
},
messages: {
noNodeAccess: 'Avoid direct Node access. Prefer using the methods from Testing Library.',
},
schema: [
{
type: 'object',
properties: {
allowContainerFirstChild: {
type: 'boolean',
},
},
},
],
},
defaultOptions: [
{
allowContainerFirstChild: false,
},
],
create(context, [{ allowContainerFirstChild = false }], helpers) {
function showErrorForNodeAccess(node) {
if (!helpers.isTestingLibraryImported(true)) {
return;
}
const propertyName = utils_1.ASTUtils.isIdentifier(node.property)
? node.property.name
: null;
const objectName = utils_1.ASTUtils.isIdentifier(node.object)
? node.object.name
: null;
if (propertyName &&
ALL_PROHIBITED_MEMBERS.some((allReturningNode) => allReturningNode === propertyName) &&
![
...utils_2.EVENTS_SIMULATORS,
'user',
].some((simulator) => simulator === objectName)) {
if (allowContainerFirstChild && propertyName === 'firstChild') {
return;
}
if (utils_1.ASTUtils.isIdentifier(node.object) &&
node.object.name === 'props') {
return;
}
context.report({
node,
loc: node.property.loc.start,
messageId: 'noNodeAccess',
});
}
}
return {
'ExpressionStatement MemberExpression': showErrorForNodeAccess,
'VariableDeclarator MemberExpression': showErrorForNodeAccess,
};
},
});