javascript - 无法找到仅用于测试的按钮组件
问题描述
我有以下组件并尝试对其进行测试。
我能够找到所有其他组件,例如Element和Table。
但是即使有 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();
});
});
解决方案
那么根据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
发现似乎很奇怪。
推荐阅读
- python - 使用 Celery 注册多个任务
- javascript - 使用 RegEx 和 Quill JS 将一组禁用词加粗?
- oracle - 使用 Oracle MERGE INTO 将两个表中的数据合并到第三个表中
- c# - 使用 Span 的 Base64 编码
在 dotnetcore 2.1 - angular - 在触发承诺后从 catch 子句访问“this”
- html - 如何删除图像创建的空白?
- javascript - 我如何嘲笑这个错误回调?
- hadoop - hive sql搜索字符串中每个字母的模式
- asp.net - PartialViews 中的输入掩码问题 - Asp.Net Core
- regex - vb.net中的正则表达式不起作用