javascript - 如何测试条件渲染组件的状态转换
问题描述
我有一个删除确认面板,当组件加载时默认禁用该面板,仅在单击删除按钮时显示
{this.state.deleteConfirmation && (
<div id="confirmation">
<Checkbox
inputId="deleteBlogConfirmation"
checked={this.state.confirmation}
onChange={this.toggleConfirmation}
></Checkbox>
<label
htmlFor="deleteBlogConfirmation"
className="p-checkbox-label"
>
Are You Sure?
</label>
<Button
label="Yes"
icon="pi pi-check"
disabled={!this.state.confirmation}
onClick={this.props.onDeleteConfirm}
className="p-button-danger"
/>
<Button
label="No"
icon="pi pi-times"
onClick={this.hideDeleteConfirmation}
className="p-button-secondary"
/>
</div>
)}
组件加载时该值为 true
this.state = {
confirmation: false,
deleteConfirmation: false
};
如果用户在确认时单击“否”,则 hideDeleteConformation 方法会隐藏此面板
hideDeleteConfirmation() {
this.setState({ deleteConfirmation: false });
}
当我断言deleteConfirmation
错误时测试失败// , Received: undefined
it("hides delete confirmation panel on clicking no button", () => {
const mockDialogFn = jest.fn();
const actionButtons = mount(
<Router>
<BlogActionButtons
rowData={rowData}
onDeleteConfirm={mockDialogFn}
/>
</Router>
);
actionButtons.find(".p-button-danger").at(0).simulate('click');
expect(actionButtons.props().deleteConfirmation).toBeTruthy(); // , Received: undefined at this line
actionButtons.find('.p-button-secondary').at(0).simulate('click');
expect(actionButtons.props().deleteConfirmation).toBeFalsy();
});
如果我切换到
expect(actionButtons.state().deleteConfirmation).toBeTruthy();
我收到TypeError: Cannot read property 'deleteConfirmation' of null
同一行的错误。
如何deleteConfirmation
在单击相应按钮时再次测试更改为真/假。
解决方案
.props()
按名称获取值,而不是它调用的函数。这就是你要找的:
expect(actionButtons.prop('onClick')).toBeTruthy()
编辑:为了测试,您首先单击然后断言 html 元素是否实际存在于 DOM 中。就个人而言,我建议find
按组件,而不是分配的 ID
const cancelButton = actionButtons.find(Button).at(1) // might not be correct depending on the rest of your component
cancelButton.prop('onClick')()
const confirmationDomElement = actionButtons.find('#confirmation')
expect(confirmationDomElement.exists()).toEqual(false)
推荐阅读
- autohotkey - 为什么我对 WinGetTitle 的调用返回一个空字符串?
- javascript - 在 react-admin 中获得对 redux 存储的访问权限
- google-cloud-pubsub - PubSub:StatusRuntimeException:来自 StreamingSubscriberConnection 的不可用
- r - 在 Shiny 中输入后运行 R 脚本
- rest - 如何将功能添加到地理服务器
- c++ - 如何提高 std::vector 的 ifstream 和 ofstream 的读写速度
- eclipselink - EclipseLink 类和 xml 混合映射
- python - 使用 pyinstaller 编译时找不到 exe 文件
- mysql - 将 2 个计数查询合并为 1 个
- java - 如何模拟 UUID?