Reactjs 材料界面';当使用Jest+;酶
我有一个React+TypeScript应用程序是SSR。我使用材料UI和SSR说明,如下所述: 我的很多组件都是有状态的,我用Jest+酶测试它们。这里有一个这样的组件:Reactjs 材料界面';当使用Jest+;酶,reactjs,typescript,jestjs,material-ui,enzyme,Reactjs,Typescript,Jestjs,Material Ui,Enzyme,我有一个React+TypeScript应用程序是SSR。我使用材料UI和SSR说明,如下所述: 我的很多组件都是有状态的,我用Jest+酶测试它们。这里有一个这样的组件: export interface CounterProps { propExample: string; classes: any; } export interface CounterState { counter: number; error: boolean; } class Counter ex
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
};
...
}
...
}
然后用酶包裹它:
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;
};
const counterProps:counterProps={
例如:“蓝色”,
类:{}
};
常量计数器状态:计数器状态={
柜台:0,,
错误:false
};
/**
*Factory函数为计数器组件创建浅层振打器。
*@功能设置
*@param{object}props-特定于此设置的组件道具。
*@param{object}state-安装程序的初始状态。
*@returns{shallowRapper}
*/
常数设置=(
道具:反搏=反搏,
状态:反状态=反状态
):ShallowRapper=>{
常量包装器=浅();
包装器。设置状态(状态);
返回包装器;
};
Jest在测试时抛出此错误:ShallowRapper::setState()只能在类组件上调用
。我想知道如何解决这个问题。无状态类组件不会出现此问题,只有有状态类组件才会出现此问题
此外,该应用程序运行完美。只是在用Jest+酶测试时,我得到了这个错误。如果我删除
with style
decorator并正常导出组件,Jest+酶测试通过。编辑:我认为您需要使用
wrapper.dive().setState(state)
因为wrapper带有HOC样式,wrapper.dive()是您的组件,编辑:我认为您需要使用
wrapper.dive().setState(state)
因为wrapper带有HOC样式,wrapper.dive()是您的组件这种情况下的不同错误:
shallowRapper::setState()只能在根上调用
您能否尝试将wrapper.children()更改为wrapper.dive()?现在,它会在检查此有状态组件是否正确呈现的其他测试中产生问题。之前通过的测试的形式为const wrapper=setup();const-appComponent=findByTestAttr(包装器,“计数器容器”);expect(appComponent.length).toBe(1)
具体来说,问题是:expect(received).toBe(expected)//Object.is equality expected:1 received:0
不同的错误在这种情况下:shallowRapper::setState()只能在根上调用
您能尝试将wrapper.children()更改为wrapper.dive()吗,它会在检查此有状态组件是否正确呈现的其他测试中产生问题。之前通过的测试的形式为const wrapper=setup();const-appComponent=findByTestAttr(包装器,“计数器容器”);expect(appComponent.length).toBe(1)
具体来说,问题是:expect(received).toBe(expected)//Object.is equality expected:1 received:0