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
|
Beta Was this translation helpful? Give feedback.
Answered by
azurespheredev
Oct 31, 2024
Replies: 1 comment 1 reply
-
You need to mock the
ParentComponent.jsimport 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; ChildComponent.jsimport React from 'react';
const ChildComponent = (props) => {
return (
<button onClick={props.onIncrement}>
Increment Count
</button>
);
};
export default ChildComponent; ParentComponent.test.jsimport React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import ParentComponent from './ParentComponent';
// Mock ChildComponent
jest.mock('./ChildComponent', () => (props) => (
<button data-testid="test-button" onClick={props.onIncrement}>
Test Button
</button>
));
describe('ParentComponent', () => {
test('increments count on button click', () => {
render(<ParentComponent />);
// Get the button and click it
const testButton = screen.getByTestId('test-button');
fireEvent.click(testButton);
// Check if the count incremented
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
}); |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
morganm94
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need to mock the
ChildComponent
and make sure theonIncrement
prop is correctly passed and called.ChildComponent
in your test file.ParentComponent
.onIncrement
function via the mockedChildComponent
.ParentComponent.js
ChildComponent.js