Solution: Unit Tests

Here’s the solution of how to write unit tests using the Jest and Vue testing libraries.

We'll cover the following

Solution

Your task was to write tests for the Pagination component. Here are the changes required:

For the src/components/pagination.spec.js file:

  • The Paginate forward test should utilize the renderPagination helper to mount the Pagination component and destructure the getByText method to access the “Next” button. A click event should be fired for the button twice. After each click, the text content of the button should be checked to confirm it matches Page 2 and Page 3 respectively.
  • The Paginate forward test should use the renderPagination helper to mount the Pagination component and destructure the getByText method. The renderPagination method should receive an object as an argument with the initialPage property set to 3. The getByText should be used to get access to the Prev button. A click event should be fired for the button twice. After each click, the text content of the button should be checked to confirm it matches Page 2 and Page 1 respectively.
  • The Can't paginate forward if the last page was reached test should mount the Pagination component with the initialPage set to 2. Then, the “Next” button should be retrieved using the getByText method and clicked twice. However, the Pagination component should still be on Page 3.
  • The Can't paginate below page 1 test should mount the Pagination component with the initialPage set to 1. Then, the “Prev” button should be retrieved using the getByText method and clicked twice. However, the Pagination component should still be on Page 1.

Let’s run the following code to understand how the solution above works.

Note: The code below may take a while to run. When the server starts, go to the app URL, and see the output.

Get hands-on with 1200+ tech skills courses.