This Babel plugin (`babel-plugin-jsx-auto-test-id`) automatically injects `data-test` attributes into the root HTML elements generated by JSX components. It infers the `data-test` ID from the component's display name, providing a consistent and maintenance-free solution for E2E test selectors. The current stable version is 1.1.0. While a formal release cadence isn't published, the 1.x versioning indicates stability and ongoing support. Its key differentiator is simplifying test automation setup by eliminating the need for manual `data-test` attribute management, which is crucial for reducing flaky tests and developer overhead in projects using frameworks like React with testing tools like Cypress or Playwright.
npm install babel-plugin-jsx-auto-test-idVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to configure `babel-plugin-jsx-auto-test-id` in a typical React project using Babel to automatically inject custom `data-test` attributes into component host elements during compilation. It includes setup for `package.json`, `.babelrc`, and an example JSX input and the necessary CLI command to perform the transformation.
Structure your JSX to have meaningful, named component wrappers where you expect `data-test` IDs. For elements within components that also need IDs, consider manual application or a different strategy.
Decide on a single strategy for `data-test` attributes: either fully automate with this plugin, or manage them manually. If using this plugin, remove any existing manual `data-test` attributes to prevent conflicts. Use the `attributeName` option if you need a different attribute name.
Ensure that your build configuration for production environments preserves component names, especially if you rely on this plugin for stable E2E selectors. Consult your minifier's documentation (e.g., Terser's `keep_fnames` option) or disable this plugin for production builds and use a different testing strategy if name obfuscation is critical.
Install the package as a development dependency: `npm install --save-dev babel-plugin-jsx-auto-test-id` or `yarn add -D babel-plugin-jsx-auto-test-id`.
Ensure `@babel/preset-react` (or an equivalent JSX preset like `@babel/preset-typescript` if using TSX) is installed and correctly listed in your Babel configuration's `presets` array.
Verify that `"jsx-auto-test-id"` is present in the `plugins` array of your `.babelrc` or `babel.config.js`. Ensure Babel is running with the correct configuration path. Check that the JSX elements are indeed component roots (e.g., `function MyComponent() { return <div>...</div>; }` not just `<div>` in global scope).