Reputation: 735
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 mocked ChildComponent
.
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 = (props) => {
return (
<button onClick={props.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)
})
})
Upvotes: 1
Views: 31
Reputation: 464
You need to mock the ChildComponent
and make sure the onIncrement
prop is correctly passed and called.
ChildComponent
in your test file.ParentComponent
.onIncrement
function via the mocked ChildComponent
.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;
import React from 'react';
const ChildComponent = (props) => {
return (
<button onClick={props.onIncrement}>
Increment Count
</button>
);
};
export default ChildComponent;
import 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();
});
});
Upvotes: 1