Search⌘ K
AI Features

Solution to Exercise

Explore how to write and implement tests for a React Task component by using mock functions and simulating user clicks. Understand test-driven development techniques to verify callback behavior and ensure proper functionality.

We'll cover the following...

The test

The first part of the exercise was to write the test itself. In case you forgot, the test must verify that the Task component will call the onToggle callback when a user clicks on it. This is one of the tests that suit the description:

JavaScript (JSX)
it('fires onToggle callback', () => {
const mockOnToggle = jest.fn();
render(<Task task={completedTask} onToggle={mockOnToggle} />);
fireEvent.click(screen.getByText(completedTask.label));
expect(mockOnToggle).toHaveBeenCalled();
});

Let’s go line-by-line. Firstly, we create the mock callback. The purpose of mock ...