1

I'm relatively new to react testing, but currently trying to use a few examples I found on the net to mock a React hook - specifically useRef.

The code below is what I found in a couple of accepted examples, but I cant understand why the following error is being generated. It 'feels' as though I'm not mocking what I think I am (i.e. useRef) but I'm struggling to understand why.

mock useRef error

Can anyone help me understand what I'm doing wrong? Thanks in advance.

Phil S
  • 123
  • 8

1 Answers1

0

You can skip last 2 lines

enter image description here

Just do this before running your test

jest.mock("react", () => {
  return {
    ...jest.requireActual("react"),
    useRef: () => {
      return {
        current: { width: 100 }
      };
    }
  };
});
Pratik Wadekar
  • 1,198
  • 8
  • 15
  • Thanks Patrik. What you've suggested definitely seems to be a step forwards, but might not be all of the answer...let me add some further context(which possibly should have been in the original question). I was attempting to mock useRef as a mechanism to manipulate the output of getBoundingClientRect() in a code snippet similar to: someRef = useRef(0); someRect = someRef .current.getBoundingClientRect(); console.log(someRect); – Phil S Jul 19 '22 at 06:38
  • but the output of the console.log statement still shows 'width' as being 0 after inserting your code snippet. I completely agree that what you've suggested is a step forwards though...I'm not seeing the original error message any longer. Would the above info help with any other suggestions? Thanks – Phil S Jul 19 '22 at 06:42
  • If your code is using `getBoundingClientRect()` and calculating some width from it I think you might need to mock `getBoundingClientRect()` too – Pratik Wadekar Jul 19 '22 at 06:45
  • It would be of great help if you could share your test suite & the component under test – Pratik Wadekar Jul 19 '22 at 06:46