React - Jest - Enzyme:如何模拟 ref 属性 [英] React - Jest - Enzyme: How to mock ref properties
问题描述
我正在为带有 ref 的组件编写测试.我想模拟 ref 元素并更改一些属性,但不知道如何操作.有什么建议吗?
//MyComp.jsxclass MyComp 扩展了 React.Component {构造函数(道具){超级(道具);this.getRef = this.getRef.bind(this);}componentDidMount() {this.setState({elmHeight: this.elm.offsetHeight});}获取引用(榆树){this.elm = 榆树;}使成为() {返回 <span ref={getRef}>里面的东西</span>}}//MyComp.test.jsxconst comp = mount( );//由于不在浏览器中,offsetHeight为0//在这里模拟 ref offsetHeight 为 100... 怎么做?期望(comp.state('elmHeight')).toEqual(100);
所以这里是解决方案,根据讨论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( );期望(comp.state('contentHeight')).toEqual(100);
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);
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);
这篇关于React - Jest - Enzyme:如何模拟 ref 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!