In order to be able to write Selenium test cases for our Webpack built React app we've added data-* attributes to certain parts of the HTML elements, example:
<div class="Component__item___2jdnc" data-app-feature="example-id"></div>
We can use these to locate elements to interact with and assert on. But, in production environment I would like to have them removed. How could that be achieved?
There are a few babel plugins that might fit the bill for this:
Attributes are automatically ignored if their value is undefined
. You can use that to your advantage and use some kind of configuration (possibly process.env.NODE_ENV
?) and a Higher-Order Component to set a prop for the data-app-feature
value only if not in production.
HOC
const appFeature = (Component, appFeature) => (props) => {
const isRunningInProduction = configuration.isProduction // or however you want to set this
return <Component appFeature={ isRunningInProduction ? appFeature : undefined } {...props} />
}
Component
const ExampleComponent = ({appFeature}) => {
return <div class="Component__item___2jdnc" data-app-feature={appFeature}></div>
}
export default appFeature(ExampleComponent, "example-id")
This answer is purely for the people who use webpack for production/development builds of the application. Do the following in webpack.prod.config. Ignore in webpack.dev.config
npm install
babel-plugin-react-remove-properties
Add it in babel loader configuration as follows
{
test: /\.(js|jsx)$/,
use: [{
loader: 'babel-loader',
options: {
plugins: [
["react-remove-properties", {"properties": ["data-test-id"]}]
]
}
}],
exclude: /node_modules/,
}
data-test-id
is the attribute we are going to use in selenium test cases to get the elements. According to the question, it is data-app-feature
The same thing we can do using below plugins.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With