React - Jest - Enzyme: How to mock ref properties
See original GitHub issueI’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 do I do it?
expect(comp.state('elmHeight')).toEqual(100);
Issue Analytics
- State:
- Created 5 years ago
- Reactions:6
- Comments:14 (5 by maintainers)
Top Results From Across the Web
React - Jest - Enzyme: How to mock ref properties
I'd like to mock the ref element and change some properties but have no idea how to. Any suggestions? // MyComp.jsx class MyComp...
Read more >React - Jest - Enzyme: How to mock ref properties-Reactjs
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) {...
Read more >Reactjs – React – Jest – Enzyme: How to mock ref properties
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...
Read more >How to mock React refs in unit tests using Jest - YouTube
Today I learned how to mock a React ref with Jest. In the past I might have used a full render (mount) in...
Read more >Continuous integration for React applications using Jest and ...
This test shows how you can easily use enzyme to query nested components, (in this case, Picker ), and assert that it is...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
This didn’t work for me when the variable of
useRef
is inuseEffect
This logs out the underlying dom element instead of the mock function since useEffect runs when the dom is rendered hence the dom element is attached to ref.
Any idea how to get around this?
How about this answer: https://stackoverflow.com/a/61789113/6463558