繁体   English   中英

如何测试条件渲染组件的状态转换

[英]How to test state transition of conditionally rendered components

我有一个删除确认面板,它在加载组件时默认禁用,仅在单击删除按钮时显示

{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为 false 且错误// , 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 for the same line。

如何在单击相应按钮时再次测试deleteConfirmation更改为 true/false。

.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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM