【问题标题】:How do I test a component method when using react-jss and enzyme?使用 react-jss 和酶时如何测试组件方法?
【发布时间】:2019-03-13 16:38:03
【问题描述】:

我基本上有这个问题:

https://github.com/airbnb/enzyme/issues/208

但我的组件被包裹在 jss withStyles 包装器中。我正在使用shallow method created by Material-UI as outlined here.

例如:

class Button extends React.Component {
  handleClick() {
    // Do something here
  }
  render() {
    // Component here
  }
}

const styles = {
     root: {}
}

export withStyles(styles)(Button); 

问题是 - wrapper.instance().handleClick() 会抛出 handleClick() is not a function

如何访问组件本身?

【问题讨论】:

    标签: reactjs testing material-ui enzyme jss


    【解决方案1】:

    您可以使用dive 访问您的组件。

    似乎 MUI 还带有“dive”功能:

    createShallow() 函数可用于这种情况。除了封装酶 API 之外,它还提供了一个潜水和 untilSelector 选项。

    import { createShallow } from '@material-ui/core/test-utils';
    
    describe('<MyComponent />', () => {
      let shallow;
    
      before(() => {
        shallow = createShallow({dive: true}); // Shallow render the one non-DOM child of the current wrapper, and return a wrapper around the result.
      });
    
      it('should work', () => {
        const wrapper = shallow(<MyComponent />);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-03
      • 2016-08-20
      • 2017-06-09
      • 2017-12-28
      • 2020-05-07
      • 2020-06-14
      • 1970-01-01
      • 2018-04-12
      相关资源
      最近更新 更多