React - Jest - Enzyme: How to mock ref properties
Asked Answered
M

2

11

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);
Milks answered 11/12, 2018 at 10:20 Comment(0)
M
8

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);
Milks answered 12/12, 2018 at 9:19 Comment(3)
Tried using this and got ` Cannot spy the getRef property because it is not a function; undefined given instead`Nippur
How do you mock on function component?Languishing
@Nippur you were probably using an arrow function, you'd need ref={this.getRef} in your componentCongest
O
1

You can mock the ref by using Object.defineProperty. For example:

Object.defineProperty(Element.prototype, 'offsetHeight', {
   value: 100,
   writable: true,
   configurable: true
});
Orate answered 1/8, 2020 at 15:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.