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.
Common errors
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.
Warnings
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.
Install
npm install babel-plugin-react-data-testid yarn add babel-plugin-react-data-testid pnpm add babel-plugin-react-data-testid Imports
- babel-plugin-react-data-testid wrong
Importing as a JavaScript module (e.g., import plugin from 'babel-plugin-react-data-testid') — it's a Babel plugin, not a runtime modulecorrectAdd 'babel-plugin-react-data-testid' to plugins in Babel config (e.g., .babelrc or babel.config.js)
Quickstart
// 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>