how to do setstate in jest code example
Example 1: setstate react js
constructor(props) {
super(props);
this.state = {
isActive: true,
};
}
checkStatus = () => {
this.setState({
'isActive' : !this.state.isActive,
});
}
Example 2: mockimplementation for setstate
import * as React from 'react';
describe('Some message', () => {
const setState = jest.fn();
const useStateMock: any = (initState: any) => [initState, setState];
afterEach(() => {
jest.clearAllMocks();
});
it('Is a test where we want to mock useState', () => {
jest.spyOn(React, 'useState').mockImplementation(useStateMock);
const wrapper = shallow(<Component {...props} />);
expect(setState).toHaveBeenCalledTimes(1);
});
});