Coder Social home page Coder Social logo

babel-plugin-jsx-remove-data-test-id's Introduction

babel-plugin-jsx-remove-data-test-id

Remove data-test-id attributes from your production builds.

Motivation

It's not usually a good idea to couple our test code with DOM element id's or CSS classnames.

  • Finding by an .o-some-class or #some-id selector couples our test to the CSS; making changes can be expensive from a maintainance point of view, whether they are coming from the CSS or the tests
  • Finding elements by DOM tag, such as <span /> or <p> can be equally as difficult to maintain; these things move around so if your looking for .first() you might get a nasty surprise

We wanted to decouple our tests from these concerns, in a way that would support both unit level tests and end to end test. Bring in:

data-test-id="some-test-id"

This package give you the ability to strip these test id's from production code.

Install

npm install babel-plugin-jsx-remove-data-test-id --save-dev

Add this to you babel config plugins

plugins: ["babel-plugin-jsx-remove-data-test-id"];

In some configurations the above will strip out the test attribute before the tests are run, causing them to fail. If this is the case for your project, you'll need to limit the plugin to non-test environments.

{
  env: {
    production: {
      plugins: ["babel-plugin-jsx-remove-data-test-id"]
    },
    test: {
      plugins: ["other-plugins"]
    }
  }
}

How to use

Add data-test-id to your react components

return (
  <div>
    <p data-test-id="component-text">{someText}</p>
  </div>
);

Peer dependency warnings

This plugin specifies Babel 7 as its peer dependency - while it also works with Babel 6 you might want to install @babel/[email protected] to get rid of unmet peer dependency warnings.

Define custom attribute name(s)

By default attributes with name data-test-id or data-testid (as used in react-testing-library) will be stripped. You can also define custom attribute names via plugin options in your babel config:

plugins: [
  [
    "babel-plugin-jsx-remove-data-test-id",
    {
      attributes: "selenium-id"
    }
  ]
];

Or if you need to strip off multiple attributes, you can define an attributes array as follows:

plugins: [
  [
    "babel-plugin-jsx-remove-data-test-id",
    {
      attributes: ["data-test-id", "selenium-id", "another-attr-to-be-stripped"]
    }
  ]
];

Make sure the plugins are part of your babel config, and build away - that's it. data-test-id's (respectively your custom named attributes) will be stripped.

babel-plugin-jsx-remove-data-test-id's People

Contributors

andarist avatar chrkhl avatar coderas avatar dependabot[bot] avatar gopro16 avatar jenniferlynparsons avatar jonamat avatar krnlde avatar leok80 avatar steven-isbell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

babel-plugin-jsx-remove-data-test-id's Issues

enhancement

i have an implementation question.
is there a reason for visiting JSXOpeningElement and iterate/validate all the attributes when you can visit JSXAttribute and do a quick match and remove ?

Add CI

CI would be useful- loads to choose from maybe travis or circle.

Doesn't remove data attribute

Here is my babel config below.
I can't understand why my babel config doesn't remove attributes. I rechecked isProd variable and value is correct

Babel config
require('dotenv').config();

module.exports = function (api) {
  api.cache(true);

  const plugins = [
    '@babel/plugin-syntax-optional-chaining',
    '@babel/plugin-syntax-dynamic-import',
    [
      '@babel/plugin-transform-react-jsx',
      {
        runtime: 'automatic',
      },
    ],
    [
      'babel-plugin-import',
      {
        libraryName: '@mui/material',
        libraryDirectory: '',
        camel2DashComponentName: false,
      },
      'core',
    ],
    [
      'babel-plugin-import',
      {
        libraryName: '@mui/icons-material',
        libraryDirectory: '',
        camel2DashComponentName: false,
      },
      'icons',
    ],
  ];
  const isProd = !['dev', 'stage'].some((env) => process.env.BE_HOST.includes(env));
  if (isProd) plugins.push(['babel-plugin-jsx-remove-data-test-id', { attributes: 'data-e2e' }]);

  return {
    plugins,
    presets: [
      [
        '@babel/preset-env',
        {
          modules: false,
          useBuiltIns: 'entry',
        },
      ],
      '@babel/preset-react',
    ],
  };
};

Webpack config
const webpack = require('webpack');
const path = require('path');
const Dotenv = require('dotenv-webpack');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const htmlWebpackPlugin = new HtmlWebPackPlugin({
  template: './src/App/index.html',
  filename: './index.html',
});

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif|mp4|ogg|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'url-loader',
        type: 'javascript/auto',
      },
      {
        test: /\.ejson$/,
        loader: 'json-loader',
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
      {
        test: /\.svg$/,
        loader: 'svg-inline-loader',
      },
      {
        test: /\.(gif|png|jpe?g|svg)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'assets/media',
              publicPath: 'assets/media',
            },
          },
          {
            loader: 'image-webpack-loader',
            options: {
              disable: true,
            },
          },
        ],
      },
      {
        test: /\.(ttf|eot|woff|woff2)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              outputPath: 'assets/fonts',
              publicPath: 'assets/fonts',
            },
          },
        ],
      },
      {
        test: /\.json$/,
        loader: 'json-loader',
      },
    ],
  },
  devServer: {
    host: 'local.dev-ipaygateway.com',
    open: true,
    historyApiFallback: true,
    allowedHosts: ['devopdata.co', 'c2-graphql-admin.devopdata.co', 'local.dev-ipaygateway.com'],
    static: {
      directory: path.resolve(__dirname, 'src', 'assets'),
      publicPath: '/',
    },
    https: true,
    port: 3000,
    client: {
      overlay: {
        errors: true,
        warnings: false,
      },
    },
  },
  resolve: {
    fallback: { url: require.resolve('url') },
    extensions: ['.js', '.jsx', '.scss', '.css'],
  },
  plugins: [
    htmlWebpackPlugin,
    new CopyWebpackPlugin({ patterns: [{ from: 'src/assets/', to: 'assets/' }] }),
    new Dotenv(),
    // new webpack.EnvironmentPlugin(['CENTIRIFUGO_BASE_URL', 'STORAGE_VERSION']),
    new MiniCssExtractPlugin({
      runtime: true,
      filename: '[name].[fullhash].css',
    }),
    new webpack.HotModuleReplacementPlugin(),
    new BundleAnalyzerPlugin({
      analyzerMode: 'disabled',
    }),
  ],
  entry: {
    'assets/js/app': `${path.resolve(__dirname, 'src/')}/index.js`,
  },
  output: {
    filename: `[name].js?ver=${new Date().getTime()}`,
    chunkFilename: `assets/js/chunk-[name].js?ver=${new Date().getTime()}`,
    path: path.resolve(__dirname, 'dist/'),
    publicPath: '/',
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    },
  },
  target: 'web',
  devtool: 'source-map',
};
Package.json config
{
  "name": "cashier2-fe",
  "version": "1.0.0",
  "proxy": "192.168.14.1",
  "description": "",
  "main": "src/index.js",
  "scripts": {
    "start": "npx webpack serve --progress --mode development",
    "build": "npx webpack --progress --mode production",
    "precommit": "lint-staged",
    "eslint": "eslint src/",
    "eslint-fix": "eslint --fix src/",
    "prepare": "husky install"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.17.10",
    "@babel/core": "^7.18.5",
    "@babel/eslint-parser": "^7.18.2",
    "@babel/plugin-proposal-class-properties": "^7.17.12",
    "@babel/plugin-transform-runtime": "^7.18.5",
    "@babel/preset-env": "^7.18.2",
    "@babel/preset-react": "^7.17.12",
    "babel-loader": "^8.2.5",
    "babel-plugin-import": "^1.13.5",
    "babel-plugin-jsx-remove-data-test-id": "^3.0.0",
    "copy-webpack-plugin": "^11.0.0",
    "css-loader": "^6.7.1",
    "dotenv": "^16.0.3",
    "dotenv-webpack": "^7.1.1",
    "eslint": "^7.32.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-config-prettier": "^6.15.0",
    "eslint-import-resolver-webpack": "^0.13.2",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-jsx-a11y": "^6.6.1",
    "eslint-plugin-prefer-arrow": "^1.2.2",
    "eslint-plugin-prettier": "^3.4.1",
    "eslint-plugin-react": "^7.31.8",
    "eslint-plugin-react-hooks": "^4.6.0",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.5.0",
    "husky": "^8.0.1",
    "image-webpack-loader": "^8.1.0",
    "json-loader": "^0.5.7",
    "lint-staged": "^10.5.4",
    "mini-css-extract-plugin": "^2.6.1",
    "prettier": "^2.7.1",
    "pretty-quick": "^3.1.3",
    "react-hot-loader": "^4.13.0",
    "redux-mock-store": "^1.5.4",
    "sass-loader": "^13.0.0",
    "style-loader": "^3.3.1",
    "svg-inline-loader": "^0.8.2",
    "url": "^0.11.0",
    "webpack": "^5.73.0",
    "webpack-bundle-analyzer": "^4.5.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.9.2",
    "yaml-loader": "^0.8.0"
  },
  "dependencies": {
    "@amcharts/amcharts4": "^4.10.12",
    "@amcharts/amcharts4-geodata": "^4.1.14",
    "@apollo/client": "^3.4.16",
    "@emotion/react": "^11.4.1",
    "@emotion/styled": "^11.3.0",
    "@mui/icons-material": "^5.0.0",
    "@mui/lab": "5.0.0-alpha.47",
    "@mui/material": "^5.0.0",
    "@mui/styles": "^5.0.0",
    "@mui/x-data-grid": "^5.2.2",
    "@sentry/react": "^6.2.5",
    "@sentry/tracing": "^6.2.5",
    "@tanstack/react-table": "^8.7.9",
    "@tanstack/react-virtual": "^3.0.0-alpha.0",
    "centrifuge": "^2.5.0",
    "classnames": "^2.2.6",
    "connected-react-router": "^6.8.0",
    "date-fns": "^2.28.0",
    "dayjs": "^1.10.4",
    "formik": "^2.2.6",
    "graphql": "^15.7.2",
    "history": "^4.9.0",
    "jsonschema": "^1.4.0",
    "lodash": "^4.17.21",
    "prop-types": "^15.8.1",
    "react": "^17.0.2",
    "react-beautiful-dnd": "^13.1.0",
    "react-day-picker": "^8.0.7",
    "react-dom": "^17.0.2",
    "react-imask": "^6.4.2",
    "react-redux": "^7.2.8",
    "react-resize-detector": "^7.1.2",
    "react-router": "^5.2.0",
    "react-router-dom": "^5.2.0",
    "react-select": "^5.3.2",
    "react-visibility-sensor": "^5.1.1",
    "redux": "^4.0.1",
    "redux-localstorage-simple": "^2.1.4",
    "redux-thunk": "^2.3.0",
    "reselect": "^4.0.0",
    "url-loader": "^4.1.1",
    "verbose": "^0.2.3",
    "whatwg-fetch": "^3.6.2",
    "xml-formatter": "^2.4.0",
    "yup": "^0.32.9"
  },
  "lint-staged": {
    "*.js": "eslint --cache --fix"
  }
}

Is there a way to use it with ts-loader?

We have

module: {
        rules: [
            {
                test: /\.ts(x?)$/,
                exclude: [/node_modules/],
                loader: 'ts-loader'
            },
            {
                test: /\.(graphql|gql)$/,
                exclude: /node_modules/,
                loader: 'graphql-tag/loader',
            }
        ]
    }

It cannot detect attributes passed as properties

If I pass a data-testid attribute as property into an object, the plugin seems not recognize it.

<TextField
       inputProps={{
         ...params.inputProps,
         'data-testid': 'search-field',
         id: 'Autocomplete',
       }}
/>

Becomes in the build:

{"data-testid":"search-field",id:"Autocomplete"}

data-id inside JSXExpressionContainer's value ....

Can the capability be added to remove data-id's from other attributes that are passed to other components as other props?

Something like this ... ?

      it('removes data-test-id inside of other attributes that are passed in as objects', () => {
        const code = '<p someOtherAttribute={{ "data-test-id": "should-be-removed" }} someOtherAttributeKeep={{ className: "should-keep" }}></p>';
        const expectedCode = '<p someOtherAttributeKeep={{ className: "should-keep" }}></p>';
        const actual = x(code, { usePlugin: true });
        const expected = x(expectedCode);
        expect(uglify(actual)).to.equal(uglify(expected));
      });

I hacked something together here ...

Cannot read property value of undefined

Offender:

const filteredProperties = properties.filter(property => attributeIdentifiers.includes(property.key.value))

I am not familiar with all the babel-ness that happens under the hood here but it looks like there may be some edge case missing again.

Not to make this sound rash but I would strongly recommend possibly reverting master to 2.0.0 until the new version is stable. I am not sure how this isn't breaking other apps or maybe my company is the only one using this in production 😄

Example Node That causes it.
This is the log of the property in the filter function on that line. key is not a property on this object which is leading to the type error.

Node {
  type: 'SpreadElement',
  start: 3998,
  end: 4009,
  loc:
   SourceLocation {
     start: Position { line: 135, column: 8 },
     end: Position { line: 135, column: 19 } },
  argument:
   Node {
     type: 'Identifier',
     start: 4001,
     end: 4009,
     loc:
      SourceLocation {
        start: [Position],
        end: [Position],
        identifierName: 'pageData' },
     name: 'pageData',
     leadingComments: undefined,
     innerComments: undefined,
     trailingComments: undefined },
  leadingComments: undefined,
  innerComments: undefined,
  trailingComments: undefined }

Readme doesn't give full picture of config requirements

Just set this up and it's great. Only issue I had was that this plugin needs to be in the production env declaration in the babel config otherwise in some testing setups it will remove the attribute and cause failing tests.

Happy to make a PR to the Readme if it would be helpful. I used this in my config to get it to work properly:

{ 
  "env": {
    "production": {
      "plugins": ["babel-plugin-jsx-remove-data-test-id"]
    }
  }
}

Is there a way to remove data-* from .js files?

Hello and thanks for the plugin.

I was wondering, I'm working on a project where the files are actually .js instead of .jsx.

Could be possible to execute the same operation in .js files?

Thanks in advance.

plugin doesnt remove "data-test-id" attribute

Hi!

I use to "react": "^16.2.0", webpack 4
install and add plugin into babel's config

presets: [
        'react',
        [
            'env',
            {
                modules: false,
                useBuiltIns: true,
                debug: true,
                // будет браться из package.json в версии 1.7 и старше
                targets: {
                    browsers: ['Chrome >= 64', 'Firefox >= 58', 'Safari >= 11', 'iOS >= 10.13', 'Edge >= 41'],
                },
            },
        ],
    ],
    plugins: [
        'external-helpers',
        'syntax-dynamic-import',
        'transform-class-properties',
        'syntax-trailing-function-commas',
        'babel-plugin-jsx-remove-data-test-id',
        ['transform-object-rest-spread', { useBuiltIns: true }],
        [
            'lodash',
            {
                id: ['lodash', 'recompose'],
            },
        ],
    ],
    env: {
        development: {
            plugins: [
                'transform-react-jsx-self',
                'transform-react-jsx-source',
                [
                    'babel-plugin-runtyper',
                    {
                        enabled: process.env.NODE_ENV !== 'production',
                    },
                ],
            ],
        },
        production: {
            plugins: [
                'transform-flow-strip-types',
                'transform-react-inline-elements',
                'transform-react-remove-prop-types',
                'transform-react-constant-elements',
                'transform-remove-console',
                'transform-remove-debugger',
            ],
        },
    }

after building I see in production code this attribute

...
            M = Object(C.a)(L.a)((function ({css: a = J.a}) {
                const {btn: b} = a
                return babelHelpers.jsx('p', {}, void 0, babelHelpers.jsx(F, {
                    'data-test-id': 'asyncIncrementBtn',
                    className: b
                }, void 0, '+~'), ' ', babelHelpers.jsx(G, {
                    'data-test-id': 'incrementBtn',
                    className: b
                }, void 0, '+'), ' ', babelHelpers.jsx(H, {'data-test-id': 'decrementBtn', className: b}, void 0, '-'))
            })),
...

I also tried to add the plugin in to production section - there is no changes (

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.