React - Jest - Enzyme: How to mock ref properties

后端 未结 2 512
我在风中等你
我在风中等你 2020-12-16 03:50

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.         


        
相关标签:
2条回答
  • 2020-12-16 04:26

    You can mock the ref by using Object.defineProperty

    `Object.defineProperty(Element.prototype, 'offsetHeight', {
       value: 100,
       writable: true,
       configurable: true
    });`
    
    0 讨论(0)
  • 2020-12-16 04:28

    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);
    
    0 讨论(0)
提交回复
热议问题