Testing the TaskList Component

Continue practicing unit testing. In this lesson, test the "TaskList" component, which renders a list of tasks in your app.

Test for TaskList

Let’s start by planning out the architecture of the component. Since it is going to be responsible for displaying the tasks, TaskList definitely needs access to those. We will use a tasks prop to pass them down.

The only feature requested from this component right now is to display whichever tasks that we pass in through the tasks prop. We will not assume which components are used to render the tasks themselves. We will only test whether the text of all the tasks is present on the page.

For now, I will skip imports and test definitions, since I covered them already. If you want to revisit it, read over some of the old lessons or take a look at the full code.

Our first test is called it('must render tasks'). In it, define a tasks array:

const tasks = ['Do this', 'Do that', 'Do nothing'];

This array will be passed to the TaskList:

render(<TaskList tasks={tasks} />);

Now, we want to check that every element of tasks is present on the webpage. This can be achieved using the getByText function:

screen.getByText('Do this');

If there is not an element with such text rendered, this line will throw an exception, failing the test. To check all three tasks, you can use a for-loop or a .forEach statement:

tasks.forEach(task => screen.getByText(task));

// or

for (const task of tasks) {
    screen.getByText(task);
}

That is it. The test is done! You can run it right here, in the integrated environment:

Get hands-on with 1200+ tech skills courses.