代码之家  ›  专栏  ›  技术社区  ›  dwjohnston

使用react jss和酵素时如何测试组件方法?

  •  -1
  • dwjohnston  · 技术社区  · 7 年前

    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 .

    如何访问组件本身?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mrchief    7 年前

    你可以用 dive 找到你的零件。

    看来梅还带了一个 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 />);
      });
    });