Can we mock a function which is written inside the component under test in Reactjs?
Asked
Active
Viewed 87 times
-2
-
I think this can help you https://stackoverflow.com/questions/43500235/jest-mock-a-function-called-inside-a-react-component – Amirhossein Rahmati Dec 23 '21 at 10:25
-
Thanks @AmirhosseinRahmati for replying. I already saw this one but that didn't help me. – hussi07 Dec 23 '21 at 10:26
-
I don't think you can mock the function written inside a react component. You'll have to refactor it outside to mock it. – Harkunwar Dec 23 '21 at 10:27
-
Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – Community Jan 01 '22 at 17:20
1 Answers
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