Qwerty
Qwerty

Reputation: 314

How can I unit test onClick if it not have an mouse click event?

I have onClick function

    private onClick(e: React.MouseEvent<HTMLButtonElement>) {
        if (e) {
            this.props.log();
        }
    }

How I can test using jest, enzyme if onClick has an event

it("should not log if has mouse event", () => {
    const onClickSpy = jest.fn();
    const logSpy = jest.fn();

    const props = {
        onClick: onClickSpy,
        log: logSpy,
    };
    const subject = mountProvider(ButtonWithLog, props);
    subject.find(ButtonWithLog).simulate("click"); // I needed without mouse event
    expect(logSpy).not.toHaveBeenCalled();
});

Upvotes: 1

Views: 1927

Answers (2)

Kavindu Wijesuriya
Kavindu Wijesuriya

Reputation: 157

it("should not log if has mouse event", () => {
    const props = {
        onClick: onClickSpy,
        log: logSpy,
    };
    const subject = mountProvider(ButtonWithLog, props);
    const onClickSpy = jest.spyOn(subject.instance(), "onClick");
    const event = { target: {} };
    subject.find(ButtonWithLog).simulate("click", event);
    expect(onClickSpy.mock.calls).to.have.length(1);
});

Upvotes: 1

Adam
Adam

Reputation: 1754

You can pass parameters into the simulate function which will be forwarded to the executing function.

const mockEvent = { target: {} };
subhect.find(...).simulate('click', mockEvent);

See more info here: Passing an event object to enzyme .simulate.

Upvotes: 0

Related Questions