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();
});
Testing the useState Hook with Enzyme js file with the following: import React from "react"; const App= () => { const [name, setName] = React. useState(""); return ( <form> <div className="row"> <div className="col-md-6"> <input type="text" placeholder="Enter your name" className="input" onChange={(e) => { setName(e.
Common way of doing it is to use the renderHook method from the React Hooks Testing Library. The next step is to figure out which cases we need to check. The best way to take off with testing is to start with two cases - in the first one we won't implement any changes to the value, in the second we'll update the value.
When using import React, { useState } from 'react' in your components, this is how you can mock useState with jest .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With