I have a parent component which calls a child component and pass a method handleIncrement
via props.
I want to test the ParentComponent
via Jest with following steps:
-
Mock the
ChildComponent
via Jest -
Call ParentComponent’s
handleIncrement
method via mockedChildComponent
.
Issue: How to pass props
to ChildComponent and call ParentComponent method
Parent Component
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const [count, setCount] = useState(0);
const handleIncrement = () => {
setCount(count + 1);
};
return (
<div>
<ChildComponent onIncrement={handleIncrement} />
<p>Count: {count}</p>
</div>
);
};
export default ParentComponent;
Child Component
import React from 'react';
const ChildComponent = ({ onIncrement }) => {
return (
<button onClick={onIncrement}>
Increment Count
</button>
);
};
export default ChildComponent;
This is my Jest test file:
How to call props.onIncrement()
?
jest.mock('ChildComponent', () => {
return {
__esModule: true,
default: () => {
const onIncrementHandler = () => {
props.onIncrement() // ==================>>>>>> How to call this ?
}
return (
<div>
<Button id='test-button' onClick={onIncrementHandler}>Test Button</Button>
</div>
)
},
}
})
describe('ParentComponent', () => {
test('test button Click', async () => {
render(<ParentComponent />)
const testButton = await screen.findByTestId('test-button')
fireEvent.click(testButton)
})
})