I have a function in my app as follows:
import React from 'react';
import { useHistory } from "react-router-dom";
const Main: React.FunctionComponent<{ data: any[] }> = ({
data: result }) => {
const history = useHistory();
return (
<>
{result?.map(inner => {
const handleClick = () => {
history.push(`/list/${result?.id}`, { item: result?.item})
}
return (
<div key={result.id} onClick={handleClick}>
<div className="inner-content">{result?.content}</div>
</div>
)
})}
</>
)
}
export default Main;
I have a test case in my tests as follows:
const mockHandleClick = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHandleClick,
}),
}));
it('Should test history push', () => {
let tree = create(<div onClick={mockHandleClick}><div class="inner-
content">Content Here</div></div>);
const button = tree.root.findByType('div')
button.props.onClick()
expect(mockHandleClick).toHaveBeenCalledTimes(1);
});
This passes, but the handleClick function still flags up in the code coverage? so I am not achieving 100% coverage.
Any Idea's?
I think you're having trouble hitting more complete code coverage because you are declaring a handleClick callback for each iterated result element object. The test appears to only select the first div.
Refactor the handleClick handler into the component body and pass a single handler to each mapped item and pass the mapped object to the handler.
const Main: React.FunctionComponent<{ data: any[] }> = ({
data: result }) => {
const history = useHistory();
const handleClick = (inner) => () => {
history.push(`/list/${inner?.id}`, { item: inner?.item });
};
return (
<>
{result?.map(inner => (
<div key={inner.id} onClick={handleClick(inner)}>
<div className="inner-content">{inner?.content}</div>
</div>
))}
</>
);
};