Babel Plugin for Removing React Test ID Props

1.0.2 · active · verified Tue Apr 21

The `babel-plugin-react-test-id` package provides a Babel plugin designed to automatically remove specified props, such as `testID`, from React components during the build process. This is particularly useful for optimizing production bundles by eliminating test-specific attributes that are not needed in the final deployed application, thereby reducing bundle size and preventing the exposure of internal testing implementation details. The current stable version is 1.0.2. As a build-time utility, its release cadence is typically slow, with updates primarily driven by changes in Babel's API or feature requests for additional prop removal customization. It differentiates itself by offering a straightforward, declarative way to strip these attributes without manual refactoring or conditional rendering logic within components, ensuring a clean separation between testing instrumentation and production code.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install `babel-plugin-react-test-id`, configure it in `.babelrc`, and use a `npm run build` script to process a React component file. The resulting output in `dist/App.js` will show that `testID` props have been successfully removed, illustrating its function in a typical development workflow.

```json
// package.json
{
  "name": "my-react-app",
  "version": "1.0.0",
  "devDependencies": {
    "@babel/cli": "^7.23.0",
    "@babel/core": "^7.23.0",
    "babel-plugin-react-test-id": "^1.0.0",
    "react": "^18.2.0"
  },
  "scripts": {
    "build": "babel src --out-dir dist --delete-dir-on-start"
  }
}
```

```json
// .babelrc
{
  "plugins": ["react-test-id"]
}
```

```javascript
// src/App.js
import React from 'react';

function Button({ children, testID, ...props }) {
  return <button data-test-button testID={testID} {...props}>{children}</button>;
}

export default function App() {
  return (
    <div>
      <h1 testID="main-heading">Welcome</h1>
      <Button testID="submit-button" onClick={() => alert('Submitted!')}>Submit</Button>
      <p testID="info-paragraph">This is some information.</p>
    </div>
  );
}
```

```bash
# Install development dependencies
npm install

# Run the Babel build process
npm run build

# Output in dist/App.js (simplified for brevity, actual output will be transpiled JS)
# // dist/App.js
# import React from 'react';
# function Button({ children, ...props }) {
#   return <button data-test-button {...props}>{children}</button>;
# }
# export default function App() {
#   return (
#     <div>
#       <h1>Welcome</h1>
#       <Button onClick={() => alert('Submitted!')}>Submit</Button>
#       <p>This is some information.</p>
#     </div>
#   );
# }
```

view raw JSON →