【问题标题】:React - Jest - Enzyme: How to mock ref propertiesReact - Jest - Enzyme:如何模拟 ref 属性
【发布时间】:2019-05-12 07:36:43
【问题描述】:

我正在为带有 ref 的组件编写测试。我想模拟 ref 元素并更改一些属性,但不知道如何。有什么建议吗?

// 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);

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    所以这里是解决方案,根据讨论 https://github.com/airbnb/enzyme/issues/1937

    可以使用非箭头函数对类进行猴子修补,其中“this”关键字被传递到正确的范围。

    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);
    

    【讨论】:

    • 尝试使用这个并得到`无法监视 getRef 属性,因为它不是函数;改为未定义`
    • 如何模拟函数组件?
    【解决方案2】:

    您可以使用 Object.defineProperty 模拟 ref

    `Object.defineProperty(Element.prototype, 'offsetHeight', {
       value: 100,
       writable: true,
       configurable: true
    });`
    

    【讨论】:

      猜你喜欢
      • 2018-03-28
      • 2022-01-19
      • 2019-10-27
      • 2019-08-12
      • 2019-08-28
      • 2019-01-29
      • 2020-11-05
      • 2017-05-18
      • 2021-10-31
      相关资源
      最近更新 更多