-2

Can we mock a function which is written inside the component under test in Reactjs?

hussi07
  • 9
  • 1

1 Answers1

0

You cannot directly mock a function but there are ways you could get it working. You could pass the function in props and call that instead of using the original function.

For example

const MyComponent = () => {
   const myFunction = () => {
      // Your code here
   };
   // rest of the code
}

You can turn this into

const MyComponent = ({myMockedFunction}) => {
   const myFunction = myMockedFunction || (() => {
      // Your code here
   });
   // rest of the code
}

Other ways include refactoring the function outside so you can use jest.mock directly.

Harkunwar
  • 653
  • 5
  • 10