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)
所以这是解决方案,根据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)
| 归档时间: |
|
| 查看次数: |
18976 次 |
| 最近记录: |