To make e2e testing easier I would like to add to each react
ponent data-ponent=
attribute with ponent name. I would like to have it done "automatically" (without adjusting render()
functions everywhere).
Anyone knows how to do it reliably for both class and function based ponents?
To make e2e testing easier I would like to add to each react
ponent data-ponent=
attribute with ponent name. I would like to have it done "automatically" (without adjusting render()
functions everywhere).
Anyone knows how to do it reliably for both class and function based ponents?
Share Improve this question asked Nov 13, 2019 at 11:18 DamaonDamaon 6121 gold badge8 silver badges16 bronze badges 2- It's difficult to give a clear answer without seeing any code. A couple of ideas pop up in my head. First off, to add attributes like that programatically you would need some event to happen like onChange or whatever and then do something like (event) => event.target.setNamedItem('data-ponent'), event.target.getNamedItem(''data-ponent').value = event.target.id (or whatever data is available). A little more info about your problem would be helpful :) – MstrQKN Commented Nov 13, 2019 at 11:36
-
@MstrQKN I need this to be reliable, so need to be on first render and not async events. I simply want to have easy searching via
document.querySelector
for react ponents to aid in writing e2e tests. – Damaon Commented Nov 13, 2019 at 20:00
2 Answers
Reset to default 5- Component name is set via static property
displayName
for each ponent. You need to set it manually. Create hoc (higher order ponent), to wrap ponent with
div
(or any other html tag) which will have required attribute.const withComponentName(WrappedComponent) => { const displayName = WrappedComponent.displayName || WrappedComponent.name || 'UnnamedComponent'; return props => ( <div data-ponent={displayName}><WrappedComponent {...props} /><div> ) }
Wrap all ponent export statements with created hoc.
export default withComponentName(YourShinyComponent)
Another option is to use this Webpack plugin to do it for you:
https://github./lemonmade/babel-plugin-react-ponent-data-attribute
If you're using create-react-app:
If you've ejected already then just follow the docs on the plugin's page ☝️
However, if you have not ejected already, then you can use either of these solutions to customize your build for a create-react-app project:
- https://github./arackaf/customize-cra
- https://github./timarney/react-app-rewired/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745159291a4614313.html
评论列表(0条)