javascript - 如何使用 Jest 和 Enzyme 测试样式组件以具有属性
问题描述
我有一个样式组件,它用一些样式包装了一个输入复选框元素。在我的应用程序中,默认情况下可能已经选中了此复选框。这是一些组件代码:
const InputCheckbox = styled.input.attrs((props) => ({
id: props.id,
type: 'checkbox',
checked: props.checked
}))`
visibility: hidden;
&:checked + label {
background-color: ${(props) => props.theme.mainColor};
border-color: ${(props) => props.theme.mainColor};
&:after {
border-left: 2px solid #fff;
border-bottom: 2px solid #fff;
}
}
`;
function Checkbox(props) {
return (
<CheckboxContainer>
<InputCheckbox
id={props.id}
checked={props.checked}
onChange={(event) => {
props.onChange(event.target.checked);
}}
/>
<CheckboxLabel id={props.id} />
</CheckboxContainer>
);
}
我正在使用 Jest 和 Enzyme 进行测试,但我找不到任何有关如何深入 Enzyme 浅层包装器以检查 InputCheckbox 中的输入是否将已选中属性设为 true 的信息。例如:
describe('Checkbox', () => {
const mockProps = {
id: 'settings-user',
checked: true,
onComplete: (id) => jest.fn(id)
};
const component = shallow(<Checkbox {...mockProps}/>);
describe('on initialization', () => {
it('Input should be checked', () => {
const inputCheckbox = component.find('InputCheckbox');
expect(inputCheckbox.props().checked).toBe(true);
});
});
});
此测试失败,因为.find()
找不到任何节点。
解决方案
您需要设置显示名称以供其查找:
InputCheckbox.displayName = 'InputCheckbox';
之后尝试component.find('InputCheckbox')
为了更方便使用babel 插件。
还可以尝试将 find 与组件构造函数一起使用。
import InputCheckbox from 'path-to-component'; ... const inputCheckbox = component.find(InputCheckbox);
- 也许在你的情况下访问子组件需要使用'mount' insted of 'shallow'。
推荐阅读
- html - 如何检查哪个弹出窗口设置为 chrome 扩展?
- java - Maven 无法解析项目的依赖关系 - 无法收集依赖关系
- python - 使用谷歌地图上的chrome webdriver滚动python3 + selenium中的元素
- php - 按日期过滤现有查询
- groovy - 使用 groovy 编辑 ODI 中的现有映射,如何不复制数据存储
- python-3.x - 由于缺少权限,Python 脚本无法访问导入的包文件
- scala - Monix 从并行任务写入单个输出流
- c++ - 为什么 leetcode c++ sort() 给出编译错误?
- javascript - NodeJs + 异步 + 谷歌身份验证 + 护照 + aws-ssm
- javascript - 为什么不在构造函数中进行 axios 调用?