0
votes

I'm trying to simulate a click with jest & enzyme and I'm new to react's testing libraries.
My component is using Material UI.

Here's the part of my code I want to test:

                    <div>
                        <Typography className={classes.instructions}>
                            All steps completed - you're finished
                        </Typography>
                        <Button onClick={handleNext} className={classes.button}>
                            Next
                        </Button>
                    </div>

In this part, I want to test the button click
Here's what I've done so far:

 let wrapper;
    const handleNext = jest.fn();
    beforeEach(() => {
        wrapper = mount(<ModelStepper handleNext={handleNext}/>)
    })
  it("handleNext increment", () => {
        const btn = wrapper.find(Button).at(1)
        expect(handleNext).toBeCalledTimes(0);
        btn.simulate("click");
        expect(handleNext).toBeCalledTimes(1);
    })

For some reason I'm not getting it to be clicked, I've already console logged the text of the button and it's the correct button I want to click.

Thanks!!

2
Is it possible for you to try react testing library? Their event firing is much more similar to what you have in a browser, and you wouldn't be testing implementation details.joshwilsonvu
Does this answer your question? React.js - Simulating a click with Enzymejoshwilsonvu
@JoshWilson I've took a look at the post you shared, and it didn't really help, because I can't really find out what the reason for the button not to be called, even though it found the button, and I didn't receive any error by clicking on it.razlevy

2 Answers

0
votes

Just change this line: const btn = wrapper.find(Button).at(1) to const btn = wrapper.find(Button).at(0).

Indexing always starts at 0.

0
votes

I was in a similar situation, but my button was within a form. For this situation what works is:

wrapper.find('button').simulate('submit');

It will fire the event and evaluate changes.