Ad

How To Test State Transition Of Conditionally Rendered Components

- 1 answer

I have a delete confirmation panel which is disabled by default when then component loads and is shown only when the delete button is clicked

{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>
)}

the value is true when component loads

this.state = {
    confirmation: false,
    deleteConfirmation: false
};

the hideDeleteConformation method hides this panel if user clicks on "No" at confirmation

hideDeleteConfirmation() {
    this.setState({ deleteConfirmation: false });
}

The test fails when I assert deleteConfirmation to be false with error // , 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();
});

If I switch to

expect(actionButtons.state().deleteConfirmation).toBeTruthy();

I get the error TypeError: Cannot read property 'deleteConfirmation' of null for the same line.

How do I test that deleteConfirmation changes to true/false again on click of respective buttons.

Ad

Answer

.props() gets values by their name, not the function that it calls. This is what you're looking for:

expect(actionButtons.prop('onClick')).toBeTruthy()

EDIT: In order to test, you first click and then assert whether or not the html element(s) actually exist in the DOM. Personally, I suggest finding by component, as opposed to assigned IDs

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)
Ad
source: stackoverflow.com
Ad