首页 > 解决方案 > 无法找到仅用于测试的按钮组件

问题描述

我有以下组件并尝试对其进行测试。
我能够找到所有其他组件,例如ElementTable。 但是即使有 2 个,也
没有找到Button对象的结果。
为什么会这样?
注意这里的Button、Element和Table组件都是我的自定义组件。

正在测试的组件

export const MyComponent = () => (
  <div>
    <div style={{ margin: 20 }}>
      <Button onClick={() => {}}>
        Click Me!
      </Button>
      <Button onClick={() => {}}>
        Click Me!
      </Button>
    </div>

    <Element name="name">
      title
    </Element>
    <div>
      <Table name="name" />
    </div>
  </div>
);

export default MyComponent;

我的测试

describe('test page', () => {

     it('should click', () => {

    const mockSelectorToggle = jest.fn();
    const defaultProps = {};
    const initialise = props => shallow(<MyComponent {...defaultProps} {...props} />);
    const wrapper = initialise();

    // all the following found
    wrapper.find('div')
    wrapper.find('div').find('div')
    wrapper.find('Element')
    wrapper.find('Table')

    // nothing found. Why only Button not findable?
    // wrapper.find('Button')
    // wrapper.find('div').find('div').find('Button')

    // looking to test it this way
    wrapper.find('Button').first().simulate('click');
    expect(mockSelectorToggle).toHaveBeenCalled();
  });
});

标签: javascriptreactjsjestjsenzyme

解决方案


那么根据Enzyme文档,有各种可用的选择器,特别是这个

https://enzymejs.github.io/enzyme/docs/api/selector.html#1-a-valid-css-selector

还有这个

https://enzymejs.github.io/enzyme/docs/api/selector.html#2-a-react-component-constructor

现在这个问题似乎与这里解释的有关:

React 组件名称和道具(Button、Button[type="submit"] 等) - 但是,请注意,强烈建议通过组件构造函数/函数而不是显示名称来查找。

我的印象是选择器正在搜索 HTMLbutton标记,而不是您的实际Button组件。

我的建议是以这种方式更改您的代码:

wrapper.find(Button);

所以基本上按照文档的建议去做:“按组件构造函数/函数而不是按显示名称查找”。

一个有趣的观点:

https://www.w3.org/International/tests/html-css/selectors-case/results-selectors-case#elemattrname

所有用户代理都将测试的 HTML 元素和属性名称视为不区分大小写。

即使Table发现似乎很奇怪。


推荐阅读