babel-plugin-react-data-testid

raw JSON →
0.2.0 verified Sat Apr 25 auth: no javascript maintenance

Babel plugin that automatically adds data-testid attributes to JSX elements based on the component name. Current version 0.2.0, stable maintenance mode. Supports custom attribute names and multiple attributes via options. Does not support class components. Compared to alternatives like babel-plugin-jsx-remove-data-test-id, this plugin focuses on adding rather than stripping test IDs.

error Error: data-testid not added to component
cause Plugin only works with functional components, not class components.
fix
Ensure your component is a function, not a class. Convert class component to function if needed.
gotcha Class components are not supported; data-testid will not be added to class components.
fix Refactor class components to functional components or manually add data-testid.
npm install babel-plugin-react-data-testid
yarn add babel-plugin-react-data-testid
pnpm add babel-plugin-react-data-testid

Shows installation, Babel config setup, and expected transformation of JSX component names to data-testid attributes.

// Install: npm install --save-dev babel-plugin-react-data-testid
// babel.config.js
module.exports = {
  presets: ['@babel/preset-env', '@babel/preset-react'],
  plugins: ['babel-plugin-react-data-testid']
};
// Before:
function App() { return <div>Hello</div>; }
const Header = () => <header>Title</header>;
// After:
// <div data-testid="App">Hello</div>
// <header data-testid="Header">Title</header>