Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  186] [ 6]  / answers: 1 / hits: 35448  / 4 Years ago, thu, february 6, 2020, 12:00:00

I have this component that I would like to test using Jest and React testing library :



export function GenericDivider({ stepsHeader = [], componentsFactory = [] }) {
const [currentPage, changePage] = useState(0);
const Component = componentsFactory[currentPage] || (() => <></>);

return (
<div className=container page__container>
...
<a
href=#
key={name}
onClick={e => {
e.preventDefault();
if (index < componentsFactory.length) changePage(index);
}}
className={`nav-link ${currentPage === index && 'active'}`}
>
{name}
</a>
...
</div>
);
}

export default memo(GenericDivider);


I would like to test if changePage is called when I fire a click, is there a way i can do that using Jest and React testing library ?



I'm new to testing and I tried this but it doesn't seem to work



it('Should call changePage when button clicked', () => {
const changePage = jest.fn();

const { container } = render(
<GenericDivider
stepsHeader={['hamid', 'walid', 'khalid']}
componentsFactory={[() => <></>, () => <></>, () => <></>]}
/>,
);

const button = container.querySelector('a');
fireEvent.click(button);
expect(changePage).toHaveBeenCalled();
});

More From » reactjs

 Answers
6

Short answer: don't.



Testing an internal state variable very much goes against the philosophy behind react-testing-library. That lib is focused on the user, and what the user can see. The user has no concept of a state variable. Instead of testing that, think of the changes the user would see, and test for that. How is the UI updated? What different markup or styling is displayed? Consider how to test from the user's perspective, and you'll find your answers.



Check out react-testing-library's Guiding Principles for more context. Then take a look through this page for guidelines on which queries make the most sense for your use case.


[#51239] Tuesday, January 28, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mattieparisp

Total Points: 612
Total Questions: 109
Total Answers: 104

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
;