- Notifications
You must be signed in to change notification settings - Fork410
React Testing using Jest : How to call parent methods passed to Mocked Child Component via props#651
-
I have a parent component which calls a child component and pass a method I want to test the
Issue: How to pass
How to call
|
BetaWas this translation helpful?Give feedback.
All reactions
You need to mock theChildComponent
and make sure theonIncrement
prop is correctly passed and called.
- Mock the
ChildComponent
in your test file. - Render the
ParentComponent
. - Trigger the
onIncrement
function via the mockedChildComponent
.
ParentComponent.js
importReact,{useState}from'react';importChildComponentfrom'./ChildComponent';constParentComponent=()=>{const[count,setCount]=useState(0);consthandleIncrement=()=>{setCount(count+1);};return(<div><ChildComponentonIncrement={handleIncrement}/><p>Count:{count}</p></div>);};exportdefaultParentComponent;
ChildComponent.js
importReactfrom'react';constCh…
Replies: 1 comment 2 replies
-
You need to mock the
ParentComponent.jsimportReact,{useState}from'react';importChildComponentfrom'./ChildComponent';constParentComponent=()=>{const[count,setCount]=useState(0);consthandleIncrement=()=>{setCount(count+1);};return(<div><ChildComponentonIncrement={handleIncrement}/><p>Count:{count}</p></div>);};exportdefaultParentComponent; ChildComponent.jsimportReactfrom'react';constChildComponent=(props)=>{return(<buttononClick={props.onIncrement}> Increment Count</button>);};exportdefaultChildComponent; ParentComponent.test.jsimportReactfrom'react';import{render,fireEvent,screen}from'@testing-library/react';importParentComponentfrom'./ParentComponent';// Mock ChildComponentjest.mock('./ChildComponent',()=>(props)=>(<buttondata-testid="test-button"onClick={props.onIncrement}> Test Button</button>));describe('ParentComponent',()=>{test('increments count on button click',()=>{render(<ParentComponent/>);// Get the button and click itconsttestButton=screen.getByTestId('test-button');fireEvent.click(testButton);// Check if the count incrementedexpect(screen.getByText('Count: 1')).toBeInTheDocument();});}); |
BetaWas this translation helpful?Give feedback.
All reactions
-
I've got a solution. Thank you for your effort! |
BetaWas this translation helpful?Give feedback.
All reactions
-
Why can't we call the handleIncrement() function directly instead of cloning it's implementation, which in this case is Count: 1. Let's say there is a handler function which is executing more than one statements, for example:- How to handle such cases? |
BetaWas this translation helpful?Give feedback.
All reactions
👍 1