React - Jest - Enzyme: How to mock ref properties

隐身守侯 提交于 2019-12-18 17:29:32

问题


I'm writing test for a component with ref. I'd like to mock the ref element and change some properties but have no idea how to. Any suggestions?

// MyComp.jsx
class MyComp extends React.Component {
  constructor(props) {
    super(props);
    this.getRef = this.getRef.bind(this);
  }
  componentDidMount() {
    this.setState({elmHeight: this.elm.offsetHeight});
  }
  getRef(elm) {
    this.elm = elm;
  }
  render() {
    return <div>
      <span ref={getRef}>
        Stuff inside 
      </span>
    </div>
  }
}

// MyComp.test.jsx
const comp = mount(<MyComp />);
// Since it is not in browser, offsetHeight is 0
// mock ref offsetHeight to be 100 here... How to?
expect(comp.state('elmHeight')).toEqual(100);

回答1:


So here's the solution, according to discussion in https://github.com/airbnb/enzyme/issues/1937

It is possible to monkey-patch the class with a non-arrow function, where "this" keyword is passed to the right scope.

function mockGetRef(ref:any) {
  this.contentRef = {offsetHeight: 100}
}
jest.spyOn(MyComp.prototype, 'getRef').mockImplementationOnce(mockGetRef);
const comp = mount(<MyComp />);
expect(comp.state('contentHeight')).toEqual(100);


来源:https://stackoverflow.com/questions/53721999/react-jest-enzyme-how-to-mock-ref-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!