'How to test ForwardRwf components with jest/enzyme?

I have such a component:

import React, { Component } from 'react';

export class TopicsList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      topics: [...],
    };
    this.references = [];
  }

getOrCreateRef(id) {
  if (!this.references.hasOwnProperty(id)) {
    this.references[id] = React.createRef();
  }
  return this.references[id];
}

  render() {
    const {
     topics
    } = this.state;

  
    return (       
        <div>
          <ul>
            {topics.map((topic) => (
                <TopicItem
                  key={topic.id}
                  topic={topic}
                  ref={this.getOrCreateRef(topic.id)}
                />
              )
            )}
          </ul>
        </div>
        
    )
  }
}
    const TopicItem = React.forwardRef((props, ref) => {
    
      return (
        <li
        >
          <p>{props.name}</p>
          <i
            className="fal fa-plus"
          />
        </li>
      );
    });

I wrote test to test how much li items will be rendered:

test('should render 3 li items', () => {
      console.log(wrapper.debug())
      expect(wrapper.find('TopicItem').length).toBe(3);
    });

but my test failed because in jest they recognized like:

<ul>
  <ForwardRef topic={{...}} />
  <ForwardRef  topic={{...}} />
  <ForwardRef  topic={{...}} />
</ul>

How can I test components that are returned with React.forwardRef? I cannot find appropriate solutions on the internet or here.



Solution 1:[1]

It is a bit late, but assigning the displayName property to the wrapped component can help. Enzyme respects displayName and uses it when creating snapshots (rendering it instead of ForwardRef in this case), and find also works with display names.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DenisG