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

Xun*_*ang 10 reactjs jestjs enzyme

我正在为带有 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);
Run Code Online (Sandbox Code Playgroud)

Xun*_*ang 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);
Run Code Online (Sandbox Code Playgroud)

  • 尝试使用它并得到` Cannot sply the getRef property because it is not a function; 未定义的给定代替` (12认同)
  • 如何模拟功能组件? (3认同)