'I want to test the button click event update the state or not?
//people-card.tsx
const PeopleCard: React.FC<PeopleListProps> = ({ peoples }) => {
const [showMore, setShowMore] = useState<number>(8);
const [btnHide, setBtnHide] = useState<boolean>(false);
const showMoreHandler: React.MouseEventHandler<
HTMLButtonElement
> = (): void => {
setShowMore((prevState) => prevState + 8);
if (showMore === 16) {
setBtnHide(true);
}
};
return (
<>
<PeopleCards data-testid='ples'>
{peoples.slice(0, showMore).map((people) => (
<PeopleList data-testid='people' key={people.login.uuid}>
<Avatar src={people.picture.large} alt='people' />
<PeopleWrapper>
<Title>Name: </Title>
<PeopleTitle changeColor={people.name.title}>
{people.name.title.length > 4
? people.name.title.slice(0, 4)
: people.name.title}
. {people.name.first} {people.name.last}
</PeopleTitle>
</PeopleWrapper>
<PeopleDetails>
<Title>Email: </Title> {people.email}
</PeopleDetails>
<PeopleDetails>
<Title>City: </Title> {people.location.city}
</PeopleDetails>
</PeopleList>
))}
</PeopleCards>
<ShowMoreBtn
onClickHandler={showMoreHandler}
hide={btnHide}
label='show more'
/>
</>
);
};
export default PeopleCard;
//showmoreBtn.tsx
interface ShowMoreBtnProps {
onClickHandler: React.MouseEventHandler<HTMLButtonElement>;
hide: boolean;
label: string;
}
export const ShowMoreBtn: React.FC<ShowMoreBtnProps> = ({
onClickHandler,
hide,
label,
}) => {
return (
<ShMoreBtn data-testid='btn' disabled={hide} onClick={onClickHandler}>
{label}
</ShMoreBtn>
);
};
here is my test.
it('calls "onClick" prop on button click', () => {
const { getByRole } = render(
<ShowMoreBtn hide={false} onClickHandler={onClickHandler} label='abc' />
);
fireEvent.click(getByRole('button'));
expect(onClickHandler).toHaveBeenCalledTimes(1);
});
Here, May be my test is wrong but I want to test when I clicked on button it should update the state showMore with 16 and showmore is equal to 16 then button should be disable. but I can not solve it how to do it. could you please help me?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|