This video is available to students only

Testing the Home Component I

In this lesson, we begin preparing tests for the Home component.

With the Home component there are two main aspects of the component we would like to test.

  1. The search input functionality at the top of the page functions the way we expect it to.

  2. The premium listings section of the homepage shows the UI we expect under the different states of the GraphQL request being made (loading, error, or success).

With this in mind, the tests in the newly created Home.test.tsx file can be structured as follows:

We'll begin by first preparing tests for the search input.

Testing the search input#

The very first test we can do with the search input in the Home component is verify that the input is provided an empty value when the Home component is first rendered. Though a test like this won't test any dynamic functionality, it will be a good test to begin with to help see how we can begin to instantiate our component in our test.

The very first thing we'll want to do in our test is render the Home component. To do so, we'll import and use the render() function from React Testing Library.

Though the above would work in simple cases, running the test above will have our unit test fail. The primary reason to this would be due to the fact that the Home component depends on context from the Apollo client since it makes a query with a React Apollo hook (useQuery) and uses the results of the query to render certain UI. By simply rendering the Home component in our test, the rendered component has no context on any Apollo functionality.

This is where we'll need to use the MockedProvider component from Apollo React Testing. The search input is independant of the status of the query made so we won't have to concern ourselves with providing valid mock GraphQL data. Instead we'll mock the GraphQL request in the loading state since this will help make our test more concise.

With the above in mind, our test will look something like the following:

Attempting to run the test above, our test will still fail. This will be due to a similar reason but now attributed to how our Home component uses components from React Router and such needs to understand the context of React Router in our test.

Start a new discussion. All notification go to the author.