Can you find a component via its title?

Viewed 32

Currently I have two separate icons using the same component -

<Icon className={classes.icon} src={xxxx} title="happy"/>
<Icon className={classes.icon} src={yyyy} title="sad"/>

I want to use Enzyme to test how many happy icons there are. Wonder if you can look it up by its title, or do I have to add another class name?

I want something like

expect(wrapper.find(Icon).title === 'happy').toHaveLength(3)

But I am sure this is not right...

1 Answers

You can use .findWhere(fn) => ShallowWrapper

Finds every node in the render tree that returns true for the provided predicate function.

and .prop(key) => Any

Returns the prop value for the root node of the wrapper with the provided key.

So that we can find the nodes by their props.

E.g.

Icon.tsx:

import React from 'react';

export function Icon({ title, className }) {
  return <i className={className}>{title}</i>;
}

Example.tsx:

import React from 'react';
import { Icon } from './Icon';

export function Example() {
  return (
    <>
      <Icon className="icon" title="happy" />
      <Icon className="icon" title="happy" />
      <Icon className="icon" title="sad" />
      <Icon className="icon" title="happy" />
    </>
  );
}

Example.test.tsx:

import { shallow } from 'enzyme';
import React from 'react';
import { Example } from './Example';

describe('70705214', () => {
  test('should pass', () => {
    const wrapper = shallow(<Example />);
    const happyIcons = wrapper.findWhere((n) => n.prop('title') === 'happy');
    const sadIcons = wrapper.findWhere((n) => n.prop('title') === 'sad');
    console.log(happyIcons.debug());
    console.log(sadIcons.debug());
    expect(happyIcons).toHaveLength(3);
    expect(sadIcons).toHaveLength(1);
  });
});

Test result:

 PASS  stackoverflow/70705214/Example.test.tsx (8.75 s)
  70705214
    ✓ should pass (18 ms)

  console.log
    <Icon className="icon" title="happy" />
    
    
    <Icon className="icon" title="happy" />
    
    
    <Icon className="icon" title="happy" />

      at Object.<anonymous> (stackoverflow/70705214/Example.test.tsx:10:13)

  console.log
    <Icon className="icon" title="sad" />

      at Object.<anonymous> (stackoverflow/70705214/Example.test.tsx:11:13)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.317 s
Related