biome-plugin-require-data-testid
Version:
This Biome plugin helps ensure that React components have the necessary testID attribute, which is crucial for effective testing of React applications.
176 lines (167 loc) • 4.49 kB
JavaScript
// src/index.js
const DEFAULT_DISABLE = [];
const DEFAULT_ENABLE = [];
module.exports = {
meta: {
docs: {
description: "Ensure specified JSX components have a 'data-testid' attribute",
},
schema: [
{
type: "object",
properties: {
disableDefaultComponents: {
type: "array",
items: { type: "string" },
},
enableComponents: {
type: "array",
items: { type: "string" },
},
},
additionalProperties: false,
},
],
},
create(context) {
const config = context.options[0] || {};
const disableDefaultComponents = config.disableDefaultComponents || DEFAULT_DISABLE;
const enableComponents = config.enableComponents || DEFAULT_ENABLE;
// Default components to check
const defaultComponents = [
"a",
"abbr",
"address",
"area",
"article",
"aside",
"audio",
"b",
"base",
"bdi",
"bdo",
"blockquote",
"body",
"br",
"button",
"canvas",
"caption",
"cite",
"code",
"col",
"colgroup",
"data",
"datalist",
"dd",
"del",
"details",
"dfn",
"dialog",
"div",
"dl",
"dt",
"em",
"embed",
"fieldset",
"figcaption",
"figure",
"footer",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"head",
"header",
"hr",
"html",
"i",
"iframe",
"img",
"input",
"ins",
"kbd",
"label",
"legend",
"li",
"link",
"main",
"map",
"mark",
"meta",
"meter",
"nav",
"noscript",
"object",
"ol",
"optgroup",
"option",
"output",
"p",
"param",
"picture",
"pre",
"progress",
"q",
"rp",
"rt",
"ruby",
"s",
"samp",
"script",
"section",
"select",
"small",
"source",
"span",
"strong",
"style",
"sub",
"summary",
"sup",
"table",
"tbody",
"td",
"template",
"textarea",
"tfoot",
"th",
"thead",
"time",
"title",
"tr",
"track",
"u",
"ul",
"var",
"video",
"wbr",
];
// Filter out disabled default components
const activeDefaults = defaultComponents.filter(
(name) => !disableDefaultComponents.includes(name)
);
// Final list of components to validate
const componentsToCheck = [...new Set([...activeDefaults, ...enableComponents])];
return {
JSXElement(node) {
const tagName = node.openingElement.name.name;
if (!componentsToCheck.includes(tagName)) return;
const hasTestId = node.openingElement.attributes.some(
(attr) =>
attr.type === "JSXAttribute" &&
attr.name &&
attr.name.name === "data-testid"
);
if (!hasTestId) {
context.report({
node,
message: `Missing 'data-testid' attribute in <${tagName}> element.`,
});
}
},
};
},
};