5

To make e2e testing easier I would like to add to each react component data-component= attribute with component 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 components?

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-component'), event.target.getNamedItem(''data-component').value = event.target.id (or whatever data is available). A little more info about your problem would be helpful :) 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 components to aid in writing e2e tests. Commented Nov 13, 2019 at 20:00

2 Answers 2

5
  1. Component name is set via static property displayName for each component. You need to set it manually.
  2. Create hoc (higher order component), to wrap component 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-component={displayName}><WrappedComponent {...props} /><div>
      )
    }
    
  3. Wrap all component export statements with created hoc.

    export default withComponentName(YourShinyComponent)

Sign up to request clarification or add additional context in comments.

Comments

1

Another option is to use this Webpack plugin to do it for you:

https://github.com/lemonmade/babel-plugin-react-component-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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.