I have a React + TypeScript app that is SSR. I use Material-UI with the SSR instructions, as described here:
https://material-ui.com/guides/server-rendering/
A lot of my components are stateful and I test them with Jest + Enzyme. Here is one such component:
export interface CounterProps {
propExample: string;
classes: any;
}
export interface CounterState {
counter: number;
error: boolean;
}
class Counter extends Component<CounterProps, CounterState> {
constructor(props: CounterProps) {
super(props);
this.state = {
counter: 0,
error: false
};
...
}
...
}
The issue happens when decorating my component as such:
export default withStyles(styles)(Counter);
and then wrapping it with Enzyme:
const counterProps: CounterProps = {
propExample: "blue",
classes: {}
};
const counterState: CounterState = {
counter: 0,
error: false
};
/**
* Factory function to create a ShallowWrapper for the Counter component.
* @function setup
* @param {object} props - Component props specific to this setup.
* @param {object} state - Initial state for setup.
* @returns {ShallowWrapper}
*/
const setup = (
props: CounterProps = counterProps,
state: CounterState = counterState
): ShallowWrapper => {
const wrapper = shallow(<Counter {...props} />);
wrapper.setState(state);
return wrapper;
};
Jest throws this error when testing: ShallowWrapper::setState() can only be called on class components
. I'd like to know how to fix this. The issue doesn't happen for stateless class components, only for stateful class components.
Also, the app runs perfectly. It's just when testing with Jest + Enzyme that I get this error. If I remove the withStyles
decorator and just export the component normally, the Jest + Enzyme tests pass.