我有一个删除确认面板,默认情况下,该面板在加载组件时处于禁用状态,并且仅在单击删除按钮时才会显示
{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>
)}
该值在组件加载时为真
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
再次变为true / false。
答案 0 :(得分:1)
.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)