Book Image

Mastering React Test-Driven Development

By : Daniel Irvine
Book Image

Mastering React Test-Driven Development

By: Daniel Irvine

Overview of this book

Many programmers are aware of TDD but struggle to apply it beyond basic examples. This book teaches how to build complex, real-world applications using Test-Driven Development (TDD). It takes a first principles approach to the TDD process using plain Jest and includes test-driving the integration of libraries including React Router, Redux, and Relay (GraphQL). Readers will practice systematic refactoring while building out their own test framework, gaining a deep understanding of TDD tools and techniques. They will learn how to test-drive features such as client- and server-side form validation, data filtering and searching, navigation and user workflow, undo/redo, animation, LocalStorage access, WebSocket communication, and querying GraphQL endpoints. The book covers refactoring codebases to use the React Router and Redux libraries. via TDD. Redux is explored in depth, with reducers, middleware, sagas, and connected React components. The book also covers acceptance testing using Cucumber and Puppeteer. The book is fully up to date with React 16.9 and has in-depth coverage of hooks and the ‘act’ test helper.
Table of Contents (21 chapters)
Free Chapter
1
Section 1: First Principles of TDD
6
Section 2: Building a Single-Page Application
12
Section 3: Interactivity
16
Section 4: Acceptance Testing with BDD

Stubbing the fetch API

The Git tag for this section is stubbing-fetch.

In this section, we'll use the fetch API to send customer data to our backend service. When the form is submitted, instead of directly calling the onSubmit prop, we'll send a POST HTTP request via the fetch API. If it returns a successful result, we'll call the onSubmit prop.

Add this next test in test/CustomerForm.test.js, right after the has a submit button test. This test is going to check that when we call fetch, we pass in the right arguments. In the Arrange phase of the test, we pass a new prop, fetch, to CustomerForm. This prop will eventually replace the onSubmit prop:

it('calls fetch with the right properties when submitting data', async () => {
const fetchSpy = spy();
render(
<CustomerForm fetch={fetchSpy.fn} onSubmit={() => {}} />
);
ReactTestUtils.Simulate...