首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Material-UI的withStyles在使用Jest +酶测试有状态类组件时导致问题

Material-UI的withStyles在使用Jest +酶测试有状态类组件时导致问题
EN

Stack Overflow用户
提问于 2019-06-02 07:40:06
回答 1查看 497关注 0票数 1

我有一个React + TypeScript应用程序,这是SSR。我将Material-UI与SSR指令一起使用,如下所述:

https://material-ui.com/guides/server-rendering/

我的很多组件都是有状态的,我用Jest + Enzyme来测试它们。下面是一个这样的组件:

代码语言:javascript
复制
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
    };
    ...
  }
  ...
}

当像这样装饰我的组件时,就会发生这个问题:

代码语言:javascript
复制
export default withStyles(styles)(Counter);

然后用酶包裹它:

代码语言:javascript
复制
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 +酶测试就会通过。

EN

回答 1

Stack Overflow用户

发布于 2019-06-03 15:34:00

编辑:我认为你需要使用

代码语言:javascript
复制
wrapper.dive().setState(state)

因为包装器是withStyles专用的,而wrapper.dive()是您的组件

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56411194

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档