React-Jest-Enzyme:如何模拟ref属性 [英] React - Jest - Enzyme: How to mock ref properties
本文介绍了React-Jest-Enzyme:如何模拟ref属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用ref编写组件的测试.我想模拟ref元素并更改一些属性,但不知道如何做.有什么建议吗?
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);
推荐答案
这是解决方案,根据 https://github.com/airbnb/enzyme/issues/1937
So here's the solution, according to discussion in https://github.com/airbnb/enzyme/issues/1937
可以使用非箭头函数对类进行猴子修补,其中"this"关键字将传递到正确的作用域.
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屋!
查看全文