Next-Generation Web

The Next-Generation Web publication is all about building the next-generation web. It covers topics about Web Design, Development, UI/UX and much more!

Follow publication

Member-only story

How to Build & Test React-Query Components in Typescript

--

React-Query is awesome! But testing components that use it can be a little tricky. This article focuses on how to test React components that rely on react-query, using Jest & Testing-Library (Typescript as a bonus!).

Prerequisites

This tutorial assumes that you have a basic understanding of:

We will be using TypeScript because it’s awesome and because it will give you superpowers (just take my word for it).

Use Case

Since this tutorial isn’t about building a full-stack application, we’re going to use the FakeStoreApi as a backend. We will create a simple component that will fetch a product by ID and display its data (see live preview)

Preview of the component we will build and test

So, let’s start coding!

Initial Setup

We will use Create React App to create the app.

npx create-react-app testing-react-query-components --template typescript

We will need to add some additional dependencies as well, like react-query and chakra-ui to create good-looking components.

yarn add react-query @chakra-ui/react @emotion/react@11 @emotion/styled@11 framer-motion@4

You can clone this repository to get all the files.

Building the Logic

The Fake Store API exposes an endpoint that will allow us to fetch a product by its ID.

GET — https://fakestoreapi.com/products/{id}

Here is the response with id=1

{
“id”: 1,
“title”: “Fjallraven — Foldsack №1 Backpack, Fits 15 Laptops”,
“price”: 109.95,
“description”: “Your perfect pack for…

--

--

Next-Generation Web
Next-Generation Web

Published in Next-Generation Web

The Next-Generation Web publication is all about building the next-generation web. It covers topics about Web Design, Development, UI/UX and much more!

Bassem Allani
Bassem Allani

Written by Bassem Allani

👨‍✈️ Airline Pilot, 👨🏻‍💻 Software Engineer, 👨🏻‍🎨 Designer, 🪄 Magician & 🎵 Musician. https://nextglabs.com

Responses (1)

Write a response