React - Jest - Enzyme:如何模拟ref属性

11

我正在为一个带 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);
2个回答

8

以下是解决方案,根据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);

15
尝试使用此代码,出现以下错误: “无法监视getRef属性,因为它不是函数,返回undefined。” - vnxyz
3
函数组件如何进行模拟测试? - Vergil C.
@vnxyz 你可能在使用箭头函数,你需要在你的组件中加入 ref={this.getRef} - Clom

1
您可以使用Object.defineProperty来模拟参考。例如:
Object.defineProperty(Element.prototype, 'offsetHeight', {
   value: 100,
   writable: true,
   configurable: true
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接