Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
React Application Architecture for Production

You're reading from  React Application Architecture for Production

Product type Book
Published in Jan 2023
Publisher Packt
ISBN-13 9781801070539
Pages 230 pages
Edition 1st Edition
Languages
Author (1):
Alan Alickovic Alan Alickovic
Profile icon Alan Alickovic

Table of Contents (13) Chapters

Preface 1. Chapter 1: Understanding the Architecture of React Applications 2. Chapter 2: Setup and Project Structure Overview 3. Chapter 3: Building and Documenting Components 4. Chapter 4: Building and Configuring Pages 5. Chapter 5: Mocking the API 6. Chapter 6: Integrating the API into the Application 7. Chapter 7: Implementing User Authentication and Global Notifications 8. Chapter 8: Testing 9. Chapter 9: Configuring CI/CD for Testing and Deployment 10. Chapter 10: Going Beyond 11. Index 12. Other Books You May Enjoy

Mocking the API

In the previous chapter, we built the application pages that use test data. The UI of the pages is complete, but the pages are not functional yet. We are using the test data without making requests to the API.

In this chapter, we will learn what mocking is and why it is useful. We will learn how to mock the API endpoints with the msw library, a great tool that allows us to create mocked API endpoints that behave as real-world API endpoints.

We will also learn how to model the data of our application entities with the @mswjs/data library.

In this chapter, we will cover the following topics:

  • Why is mocking useful?
  • Introduction to MSW
  • Configuring data models
  • Configuring request handlers for API endpoints

By the end of this chapter, we will learn how to generate fully featured mocked APIs with data models set in place, which will make our code base less dependent on external APIs during development.

Technical requirements

Before we get started, we need to set up our project. To be able to develop our project, we will need the following things installed on our computer:

  • Node.js version 16 or above and npm version 8 or above

There are multiple ways to install Node.js and npm. Here is a great article that goes into more detail: https://www.nodejsdesignpatterns.com/blog/5-ways-to-install-node-js.

  • Visual Studio Code (VS Code) (optional) is currently the most popular editor/IDE for JavaScript/TypeScript, so we will be using it. It is open source, has great integration with TypeScript, and we can extend its features via extensions. It can be downloaded from here: https://code.visualstudio.com/.

The code files for this chapter can be found here: https://github.com/PacktPublishing/React-Application-Architecture-for-Production

The repository can be cloned locally with the following command:

git clone https://github.com/PacktPublishing/React-Application...

Why is mocking useful?

Mocking is the process of simulating parts of the system, meaning they are not production-ready but fake versions that are useful for development and testing.

You may ask yourself, Why do we want to bother with setting a mocked API? There are several benefits of having the API mocked:

  • Independence of external services during development: A web application usually consists of many different parts such as the frontend, the backend, external third-party APIs, and so on. When developing our frontends, we want to be as autonomous as possible without getting blocked by some parts of the system that are not functional. If the API of our application is broken or unfinished, we should still be able to proceed with developing the frontend part of the application.
  • Good for quick prototyping: Mocked endpoints allow us to prototype the application quicker since they don't require any additional setup such as the backend server, database, and so on. Very...

Introduction to MSW

MSW is a tool that allows us to create mocked APIs. It works as a service worker that intercepts any API request that has its mocked version defined. We can inspect the requests and responses in the Network tab of our browser the same way as if we were calling the real API.

To get a high-level overview of how it works, let’s take a look at the diagram provided on their website:

Figure 5.1 – MSW workflow diagram

One great thing about MSW is that our application will behave the same as if it were using a real API, and it’s pretty trivial to switch to using the real API by turning mocked endpoints off and not intercepting requests.

Another great thing is that since the interception happens at the network level, we will still be able to inspect our requests in the Network tab of the browser dev tools.

Configuration overview

We already have the MSW package installed as a dev dependency. The msw mocked API can...

Configuring data models

For data modeling our application, we will be using the data library from MSW, which is very useful and simple to use to manipulate the data in a similar way an object-relational mapper (ORM) on the backend would.

To make our request handlers functional, we could just hardcode the responses, but where is the fun in that? With MSW and its data library, we can build a mocked backend that is fully functional with the business logic included should we decide to implement it.

To configure our data models, let’s open the src/testing/mocks/db.ts file and add the following:

import { factory, primaryKey } from '@mswjs/data';
import { uid } from '@/utils/uid';
const models = {
  user: {
    id: primaryKey(uid),
    createdAt: Date.now,
    email: String,
    password: String,
    organizationId: String,
  },
 ...

Configuring request handlers for API endpoints

In this section, we will define handlers for our application. As already mentioned, a handler in MSW is a function that, if defined, will intercept any matching requests, and instead of sending the requests to the network, it will modify them and return the mocked response.

API utils

Before getting started, let’s take a quick look at the src/testing/mocks/utils.ts file, which includes some utilities we will be using for handling the business logic of our API handlers:

  • authenticate accepts user credentials, and if they are valid, it will return the user from the database together with the authentication token.
  • getUser returns a test user object.
  • requireAuth returns the current user if the token in the cookie is available. It can optionally throw an error if the token does not exist.

Before getting started, let’s include all handlers in the configuration. Open the src/testing/mocks/handlers/index...

Summary

In this chapter, we learned about mocking the API. We introduced the MSW library, which is a great tool for mocking APIs in an elegant way. It can work both in the browser and on the server. It is super useful for prototyping and testing the application during development.

In the next chapter, we will integrate the API layer of the application, which will consume the endpoints we just created.

lock icon The rest of the chapter is locked
You have been reading a chapter from
React Application Architecture for Production
Published in: Jan 2023 Publisher: Packt ISBN-13: 9781801070539
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}