How did I test my pagination component
that lives in an environment was built using react, typescript, vite, tailwindcss, vitest, testing library, and eslint.
It was fun testing a component created from scratch by me : )
I was given an interview task to convert a Figma design into a modern React application. I wanted to create widgets from scratch, in order to obtain an easy-to-maintain and easy-to-test codebase.
When creating the pagination component, I had to think of its fundamental building blocks step by step. It was a bit tiring but later those steps helped me to create test cases properly. I know, developer should write tests before writing the actual code, but I don’t know, maybe this was the writing tests beforehand : )
Infrastructure
I wanted to create a modern testing infrastructure, so I did a lot of reading. The biggest take away from those readings for me is that I’d like to test my component by simulating end-user behaviors. So I implemented Vitest, Jest Dom, Testing Library, and their eslint plugins.
Implementation
To be able to write tests and learn along the way, I started creating tests from easy to relatively hard.
Rendering the component
To render the component into the testing environment, I used the render
function of the testing library.
const onChangePageNo = vi.fn();
render(
<Pagination
pageNo={1}
perPageItemSize={2}
totalCount={14}
onChangePageNo={onChangePageNo}
/>,
);
Finding elements
To find elements in the document, I used the screen
module of the testing library. There are getByRole
, findByRole
, and queryByRole
methods of the screen
to find elements. You can fully understand these by following “How To Test a React App with Jest and React Testing Library” by Alyssa Holland.
In short, we use
getByRole
to find an element present in the document,findByRole
to find an element that requires some time to render,queryByRole
if we expect not to find an element in the document.
const prevButton = screen.getByRole("button", { name: /Prev/ });
const separator = screen.queryByRole("radio", { name: "..." });
Testing being in the document
Before testing any event, I checked if my page buttons are in the document.
expect(pageButton).toBeInTheDocument();
Testing whether it is called
To check button click events, I created a mock event handler using vi.fn()
then checked whether it is called after being triggered by userEvent of the testing library.
const onChangePageNo = vi.fn();
...
userEvent.click(nextButton);
...
expect(onChangePageNo).toHaveBeenCalledTimes(1);
Conclusion
This project was a great assignment to learn designing, testing and to refresh some of my knowledge. The feedback on my technical assignment was positive.
Thank you for reading! I hope you have found this post helpful.
You can check out the source code on github, and live preview on codesandbox.