【问题标题】:Can you find a component via its title?你能通过它的标题找到一个组件吗?
【发布时间】:2022-01-14 10:53:58
【问题描述】:

目前我有两个使用相同组件的单独图标 -

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

我想用 Enzyme 来测试一下有多少个开心的图标。不知道您是否可以通过它的标题查找它,还是我必须添加另一个类名?

我想要类似的东西

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

但我确定这是不对的……

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme


    【解决方案1】:

    您可以使用.findWhere(fn) => ShallowWrapper

    查找渲染树中为提供的谓词函数返回 true 的每个节点。

    .prop(key) => Any

    使用提供的键返回包装器根节点的 prop 值。

    这样我们就可以通过它们的道具找到节点。

    例如

    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);
      });
    });
    

    测试结果:

     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
    

    【讨论】:

    • 非常感谢!!!这太有用了!! wrapper.findWhere 工作!!
    猜你喜欢
    • 2013-11-10
    • 2020-01-11
    • 2010-12-29
    • 1970-01-01
    • 2014-01-19
    • 1970-01-01
    • 2018-01-06
    • 2012-04-12
    • 1970-01-01
    相关资源
    最近更新 更多