mercredi 30 septembre 2020

Unexpected results in testing a stateful React component with hooks?? (Jest)

I am new to testing, creating simple component with counter state and useState react hook that increment the counter when a button is clicked:

Component:

const Counter= () => {
    const[counter, setCounter] = useState(0);

    const handleClick=() => {
        setCounter(counter + 1);
    }

    return (
        <div>
            <h2>{counter}</h2>
            <button onClick={handleClick} id="button">increment</button>
        </div>
    )
}

Counter.test.js:

it('increment counter correctly', () => {
    let wrapper = shallow(<Counter/>);
    const counter  = wrapper.find('h2');
    const button = wrapper.find('button');
    button.simulate('click')
    console.log(counter.text()) // 0
})

Logging counter.text() after simulating button click print 0 instead of 1; and when i tried to spy on useState, i got the same problem:

it('increment counter correctlry', () => {
    let wrapper = shallow(<Card />);
    const setState = jest.fn();
    const useStateSpy = jest.spyOn(React, 'useState');

    useStateSpy.mockImplementation((init) => [init, setState]);
     const button = wrapper.find("button")
     button.simulate('click');
     expect(setState).toHaveBeenCalledWith(1);
})

This test fails and i get this error after running the test:

Expected: 1
Number of calls: 0

What am i doing wrong??

Aucun commentaire:

Enregistrer un commentaire