我有一个React + TypeScript应用程序,这是SSR。我将Material-UI与SSR指令一起使用,如下所述:
https://material-ui.com/guides/server-rendering/
我的很多组件都是有状态的,我用Jest + Enzyme来测试它们。下面是一个这样的组件:
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
};
...
}
...
}当像这样装饰我的组件时,就会发生这个问题:
export default withStyles(styles)(Counter);然后用酶包裹它:
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在测试时抛出这个错误:ShallowWrapper::setState() can only be called on class components。我想知道怎么解决这个问题。这个问题不会发生在无状态类组件上,只会发生在有状态类组件上。
此外,该应用程序运行得很好。只是在使用Jest +酶测试时,我得到了这个错误。如果我删除withStyles装饰器并正常导出组件,Jest +酶测试就会通过。
发布于 2019-06-03 15:34:00
编辑:我认为你需要使用
wrapper.dive().setState(state)因为包装器是withStyles专用的,而wrapper.dive()是您的组件
https://stackoverflow.com/questions/56411194
复制相似问题