I have a component that has few useState hooks:
const [resizing, setResizing] = React.useState(false);
const [x, setX] = React.useState(0);
const [y, setY] = React.useState(0);
And in some places I am calling more than one hook at a time, for example here in onResize
, I am calling both setResizing
and setX
or setY
hook:
<ResizableBox
height={520}
width={370}
minConstraints={[370, 520]}
maxConstraints={[Infinity, Infinity]}
className={classes.resizable}
onResize={(e) => {
if (e.movementX !== 0) {
setResizing(true);
setX((prev) => prev + e.movementX);
} else if (e.movementY !== 0) {
setResizing(true);
setY((prev) => prev + e.movementY / 2);
}
}}
onResizeStop={() => {
setResizing(false);
}}
>
I am used to testing class components where it is easy to test state changes.
I would like to test it with something like this:
const setXSpy = jest.spyOn(React, 'setX');
const setYSpy = jest.spyOn(React, 'setY');
const setResizeSpy = jest.spyOn(React, 'setResize');
it('calls useState hooks correctly', () => {
resizableBox.props.onResize({movementX: 1});
expect(setXSpy).toHaveBeenCalledWith(1);
expect(setYSpy).not.toHaveBeenCalled();
expect(setResizeSpy).toHaveBeenCalledWith(true);
});
But, I am not sure how test hooks like that in this example?