# Тестирование React Native с React Query и Zustand

By Tarik Pinarci (https://tarikpinarci.com). Published 2022-04-30. Canonical: https://tarikpinarci.com/ru/blog/testing-react-native-with-react-query-and-zustand

React Native стал популярным выбором для создания мобильных приложений благодаря быстрому циклу разработки и кроссплатформенности. Чтобы получить максимум от разработки на React Native, разработчики часто берут сторонние библиотеки, такие как React-Query и Zustand, для загрузки данных и управления состоянием. React-Query даёт гибкий и эффективный способ загружать, кэшировать данные и управлять ими, а Zustand делает управление состоянием простым и мощным благодаря минималистичному подходу.

В этой статье мы разберём, как эффективно тестировать приложения на React Native, которые используют эти две библиотеки. В качестве примера возьмём простое приложение магазина и приведём подробные примеры, которые помогут понять процесс тестирования. К концу статьи у вас будет хорошее понимание того, как использовать и тестировать React-Query и Zustand в приложениях на React Native

### 1. Настройка окружения

Для инициализации приложения магазина мы будем использовать React Native версии **_0.71.2_**, а для загрузки данных и управления состоянием React-Query (Tanstack query) версии **_3.39.3_** и Zustand версии **_4.3.2_**. Полный исходный код готового приложения я выложу на GitHub, так что если хотите сразу посмотреть его в работе, можете [перейти по ссылке, которая приведена в конце статьи](#8fa3). Так вы сможете следить за примерами и видеть полный код приложения.

### 1.1. Настройка API магазина

Чтобы показать эффективные приёмы тестирования в React Native, мы будем использовать в качестве API [https://fakestoreapi.com](https://fakestoreapi.com/). Наше приложение магазина будет загружать набор товаров из этого API и показывать подробную информацию о каждом товаре. У FakeStoreProduct есть и другие REST API, которыми можно было бы воспользоваться, но это усложнило бы пример и отвлекло от главной цели статьи.

Чтобы общаться с API по всему приложению, мы создадим экземпляр axios.

### 1.2. Настройка экземпляра axios

```tsx
import axios from "axios";

export const BASE_URL = "https://fakestoreapi.com";

export const api = axios.create({
  baseURL: BASE_URL,
});
```

Следующим шагом будет настройка react-query для нашего API.

### 1.3. Создание key-factory для управления кэшированием запросов

Что такое key-factory?

[**_По своей сути TanStack Query управляет кэшированием запросов за вас на основе ключей запросов. Ключ запроса на верхнем уровне должен быть массивом и может быть как простым массивом с одной строкой, так и сложным массивом из множества строк и вложенных объектов. Если ключ запроса сериализуем и уникален для данных запроса, его можно использовать!_**](https://tanstack.com/query/latest/docs/react/guides/query-keys)

Хотя простота нашего приложения не обязательно требует кэширования, мы всё равно воспользуемся мощными возможностями кэширования React-Query. Поэтому мы создадим простую фабрику ключей, которая показана ниже.

```tsx
export const productKeyFactory = {
  products: ["all-products"],
  productById: (id: number) => [...productKeyFactory.products, id],
} as const;
```

### 1.4. Загрузка товаров с помощью react-query

```tsx
import { AxiosError } from "axios";
import { useQuery, UseQueryOptions } from "react-query";
import { api } from "../axios.instance";
import { productKeyFactory } from "./key-factory";
import { Product } from "./types";

export const getAllProducts = async () => {
  return (await api.get<Array<Product>>("/products")).data;
};

export const useGetAllProducts = (
  options?: UseQueryOptions<
    Array<Product>,
    AxiosError,
    Array<Product>,
    readonly [string]
  >
) => {
  return useQuery({
    queryKey: [...productKeyFactory.products],
    queryFn: getAllProducts,
    ...options,
  });
};
```

Выше мы создали hook useGetAllProducts для загрузки товаров и использовали ключ запроса, созданный в предыдущем разделе.

### 1.5. Загрузка подробностей товара с помощью react-query

```tsx
import { AxiosError } from "axios";
import { useQuery, UseQueryOptions } from "react-query";
import { api } from "../axios.instance";
import { productKeyFactory } from "./key-factory";
import { Product } from "./types";

export const getProductById = async (productId: number) => {
  return (await api.get<Product>(`/products/${productId}`)).data;
};

export const useGetProductById = (
  productId: number,
  options?: UseQueryOptions<
    Product,
    AxiosError,
    Product,
    readonly (string | number)[]
  >
) => {
  return useQuery({
    queryFn: () => getProductById(productId),
    queryKey: [...productKeyFactory.productById(productId)],
    ...options,
  });
};
```

Почти то же самое, что и предыдущий hook, только на этот раз hook useGetProductById будет загружать подробную информацию о товаре по его id.

### 1.6. Тип товара

Не будем пропускать этот шаг и посмотрим, как выглядит объект товара.

```tsx
export interface Product {
  id: number;
  title: string;
  price: number;
  description: string;
  category: string;
  image: string;
  rating: Rating;
}

export interface Rating {
  rate: number;
  count: number;
}
```

### 1.7. А вот и zustand: управление товарами в корзине

В приложении будут базовые функции: пользователи могут добавлять товары в корзину и удалять их оттуда, а также менять количество отдельных товаров. Кроме того, пользователь может полностью очистить корзину. Всем этим будет управлять Zustand. Ниже рассмотрим реализацию.

```tsx
import { create } from "zustand";
import { shallow } from "zustand/shallow";
import { Product } from "../api/product";

export type ProductInBasket = {
  product: Product;
  quantity: number;
};

export const updateProductQuantity = (
  productsInBasket: Array<ProductInBasket>,
  productId: number,
  updateType: "increase" | "decrease"
) => {
  return productsInBasket.map((productInBasket) => {
    if (productInBasket.product.id === productId) {
      return {
        ...productInBasket,
        quantity:
          updateType === "increase"
            ? productInBasket.quantity + 1
            : productInBasket.quantity - 1,
      };
    }
    return productInBasket;
  });
};

export const increaseProductQuantityInBasket = (
  productsInBasket: Array<ProductInBasket>,
  productId: number
) => {
  return updateProductQuantity(productsInBasket, productId, "increase");
};

export const decreaseProductQuantityInBasket = (
  productsInBasket: Array<ProductInBasket>,
  productId: number
) => {
  return updateProductQuantity(productsInBasket, productId, "decrease");
};

export interface ProductStore {
  productsInBasket: Array<ProductInBasket>;
  actions: {
    addProductToBasket: (val: Product) => void;
    removeProductFromBasket: (productId: number) => void;
    increaseProductQuantityInBasket: (productId: number) => void;
    decreaseProductQuantityInBasket: (productId: number) => void;
    resetAllProductsInBasket: () => void;
  };
}

export const useProductStore = create<ProductStore>((set, get) => ({
  productsInBasket: [],
  actions: {
    addProductToBasket: (product) =>
      set({
        productsInBasket: [
          ...get().productsInBasket,
          { product: product, quantity: 1 },
        ],
      }),
    removeProductFromBasket: (productId) =>
      set({
        productsInBasket: [
          ...get().productsInBasket.filter(
            (productInBasket) => productInBasket.product.id !== productId
          ),
        ],
      }),
    increaseProductQuantityInBasket: (productId) => {
      set({
        productsInBasket: increaseProductQuantityInBasket(
          get().productsInBasket,
          productId
        ),
      });
    },
    resetAllProductsInBasket: () => set({ productsInBasket: [] }),
    decreaseProductQuantityInBasket: (productId) => {
      set({
        productsInBasket: decreaseProductQuantityInBasket(
          get().productsInBasket,
          productId
        ),
      });
    },
  },
}));

export const useProductActions = () =>
  useProductStore((state) => state.actions);

export const useProductsInBasket = () =>
  useProductStore((state) => state.productsInBasket, shallow);
export const useProductsInBasketCount = () =>
  useProductStore((state) => state.productsInBasket.length);
export const useProductInBasketQuantityById = (productId: number | undefined) =>
  useProductStore(
    (state) =>
      state.productsInBasket.find(
        (productInBasket) => productInBasket.product.id === productId
      )?.quantity
  );
```

Первая часть кода определяет три функции: updateProductQuantity, increaseProductQuantityInBasket и decreaseProductQuantityInBasket. Это вспомогательные методы для изменения количества товара в корзине. Функция updateProductQuantity принимает на вход массив объектов, соответствующий productsInBasket, ID товара и тип изменения (увеличение или уменьшение) и возвращает новый массив productsInBasket с обновлённым количеством для указанного товара.

Интерфейс ProductStore описывает схему store товаров. В нём два свойства:

1. productsInBasket: массив объектов ProductInBasket, представляющих товары в корзине.

1. actions: объект с функциями для управления товарами в корзине, включая добавление товара, удаление товара, увеличение и уменьшение его количества и очистку корзины.

Hook useProductStore создаётся с помощью функции create из Zustand. Он возвращает store товаров с его state и actions.

Остальные hooks, useProductActions, useProductsInBasket, useProductsInBasketCount и useProductInBasketQuantityById, это селекторы, построенные на hook useProductStore. Они дают доступ к отдельным частям store товаров, например к actions или к количеству избранных товаров.

Также стоит упомянуть, что в useProductsInBasket мы использовали shallow из zustand. Дело в том, что массив объектов, который возвращает useProductsInBasket, будет вызывать повторный рендер, поскольку объекты не являются [**_примитивными типами_**](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)\*, поэтому [мы просто говорим zustand, что хотим сравнивать объект поверхностно, передавая функцию поверхностного сравнения.](https://github.com/pmndrs/zustand#selecting-multiple-state-slices)

### 1.8. Установка пакетов, необходимых для тестирования

Теперь можно перейти к той части, которая нас интересует больше всего: к тестированию. Мы будем использовать следующие пакеты:

- [jest (29.4.1)](https://jestjs.io/)

- [ts-jest (29.0.5)](https://github.com/kulshekhar/ts-jest)

- [@testing-library/react-hooks (8.0.1)](https://react-hooks-testing-library.com/)

- [@testing-library/react-native (11.5.1)](https://callstack.github.io/react-native-testing-library/)

- [Mock service worker, он же MSW\*(1.0.0)](https://mswjs.io/)\*

Ради краткости и чтобы не растягивать статью, мы опустим часть шагов по настройке тестового окружения, например jest.config.js и ts-jest .

Посмотреть, как в итоге настроено тестовое окружение, можно в полном исходном коде по ссылке в конце статьи.

### 1.9. Мокирование данных API с помощью MSW

Чтобы эффективно тестировать приложение с react-query, нам нужно замокать API. Для этого мы воспользуемся mock service worker (MSW).

```tsx
import { rest } from "msw";
import { setupServer } from "msw/node";
import { BASE_URL } from "../../src/api/axios.instance";
import {
  GET_ALL_PRODUCTS_MOCK_RESPONSE,
  GET_PRODUCT_BY_ID_MOCK_RESPONSE,
} from "./mock-data";

const getAllProductsUrl = BASE_URL + "/products";
const getProductByIdUrl = BASE_URL + `/products/:id`;

const getAllProductsHandler = rest.get(getAllProductsUrl, (_req, res, ctx) => {
  return res(ctx.status(200), ctx.json(GET_ALL_PRODUCTS_MOCK_RESPONSE));
});

const getProductByIdHandler = rest.get(getProductByIdUrl, (_req, res, ctx) => {
  return res(ctx.status(200), ctx.json(GET_PRODUCT_BY_ID_MOCK_RESPONSE));
});

const handlers = [getAllProductsHandler, getProductByIdHandler];

export const mswServer = setupServer(...handlers);

const getAllProductsFailedHandler = rest.get(
  getAllProductsUrl,
  (_req, res, ctx) => {
    return res(ctx.status(500));
  }
);

const getProductByIdFailedHandler = rest.get(
  getProductByIdUrl,
  (_req, res, ctx) => {
    return res(ctx.status(500));
  }
);

export const setupGetAllProductsFailedHandler = () =>
  mswServer.use(getAllProductsFailedHandler);

export const setupGetProductByIdFailedHandler = () =>
  mswServer.use(getProductByIdFailedHandler);
```

В коде выше мы импортируем нужные модули и настраиваем обработчики MSW. Мы создаём два мок-эндпоинта: один для загрузки всех товаров, другой для загрузки товара по id, и оба возвращают успешный ответ. Чтобы тестирование было полным, мы также создаём обработчики с ошибкой для этих двух эндпоинтов, чтобы имитировать и тестировать сценарии сбоя.

Чтобы завершить настройку моков, нам нужно использовать объект mswServer в jest.setup.js . Мы просто инициализируем mswServer перед всеми тестами, сбрасываем обработчики после каждого теста и в конце его выключаем.

```tsx
import "react-native-gesture-handler/jestSetup";
import { mswServer } from "./__mocks__/msw/handlers";

jest.useFakeTimers();

// https://mswjs.io/docs/getting-started/integrate/node#setup

// Establish API mocking before all tests.
beforeAll(() => mswServer.listen());
// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => mswServer.resetHandlers());
// Clean up after the tests are finished.
afterAll(() => mswServer.close());

// Silence the warning: Animated: `useNativeDriver` is not supported because the native animated module is missing
jest.mock("react-native/Libraries/Animated/NativeAnimatedHelper");
```

Теперь API замокан, и его можно использовать в тестах. Но это ещё не всё. Нам также нужно настроить zustand для тестирования [по документации, которую они предоставили.](https://docs.pmnd.rs/zustand/guides/testing) Это позволит [сбрасывать state между тестами](https://docs.pmnd.rs/zustand/guides/testing), когда zustand используется в тестах.

### 1.10. Настройка zustand для тестирования

```tsx
// https://docs.pmnd.rs/zustand/guides/testing#resetting-state-between-tests-in-react-dom
const { create: actualCreate } = jest.requireActual("zustand"); // if using jest
import { act } from "@testing-library/react-native";

// a variable to hold reset functions for all stores declared in the app
const storeResetFns = new Set();

// when creating a store, we get its initial state, create a reset function and add it in the set
export const create = (createState) => {
  const store = actualCreate(createState);
  const initialState = store.getState();
  storeResetFns.add(() => store.setState(initialState, true));
  return store;
};

// Reset all stores after each test run
beforeEach(() => {
  act(() => storeResetFns.forEach((resetFn) => resetFn()));
});
```

Здесь важно положить этот файл в правильную директорию в зависимости от тестового окружения. Поскольку мы используем jest, файл нужно разместить в **mocks**/zustand.js, [как описано в документации](https://docs.pmnd.rs/zustand/guides/testing).

Возможно, вы уже устали от настройки (тестового) окружения, но мне всё равно нужно было это описать, потому что это скелет нашего окружения.

А теперь перейдём к разделу, в котором мы создаём экран для отображения товаров.

### 2. Обзор экрана списка товаров

Как мы уже говорили, у нас будет экран для отображения товаров. Посмотрим на полный код экрана списка товаров:

```tsx
import { DefaultTheme } from "@react-navigation/native";
import * as React from "react";
import {
  FlatList,
  ListRenderItemInfo,
  RefreshControl,
  StyleSheet,
  Text,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { Product, useGetAllProducts } from "../api/product";
import ProductListCard from "../components/product-list-card";
import ScreenLoading from "../components/screen-loading";
import Spacing from "../components/spacing";
import useRefreshByUser from "../hooks/useRefreshByUser";
import { RouteNames } from "../navigation/route-names";
import { ProductListScreenProps } from "../navigation/types";
import { useProductActions, useProductsInBasket } from "../store/product";
import { COMMON_STYLES } from "../theme/common-styles";

type Props = ProductListScreenProps;

const ProductListScreen: React.FC<Props> = ({ navigation }) => {
  const { data, isLoading, refetch, isError, isSuccess } = useGetAllProducts();

  const { isRefetchingByUser, refetchByUser } = useRefreshByUser(refetch);

  const { addProductToBasket, removeProductFromBasket } = useProductActions();
  const productsInBasket = useProductsInBasket();

  const onAddToBasketPress = React.useCallback(
    (product: Product) => () => {
      if (
        productsInBasket.find(
          (productInBasket) => productInBasket.product.id === product.id
        )
      ) {
        removeProductFromBasket(product.id);
      } else {
        addProductToBasket(product);
      }
    },
    [addProductToBasket, productsInBasket, removeProductFromBasket]
  );

  const onProductCardPress = React.useCallback(
    (productId: number) => () => {
      navigation.navigate(RouteNames.productDetail, { id: productId });
    },
    [navigation]
  );

  const renderItemSeparator = () => (
    <Spacing
      backgroundColor={DefaultTheme.colors.background}
      height={COMMON_STYLES.screenPadding}
    />
  );

  const getKeyExtractor = (item: Product) => item.id.toString();

  const renderItem = ({ item: product }: ListRenderItemInfo<Product>) => {
    return (
      <ProductListCard
        {...product}
        testID={`product-list-card-${product.id}`}
        basketButtonTestID={`basket-button-${product.id}`}
        isInBasket={
          typeof productsInBasket.find(
            (productInBasket) => productInBasket.product.id === product.id
          ) !== "undefined"
        }
        onAddToBasketPress={onAddToBasketPress(product)}
        onPress={onProductCardPress(product.id)}
      />
    );
  };

  if (isLoading) {
    return <ScreenLoading />;
  }

  return (
    <SafeAreaView style={COMMON_STYLES.flex} edges={["bottom"]}>
      {isError && (
        <View style={COMMON_STYLES.flexCenter}>
          <Text>An error occurred</Text>
        </View>
      )}

      {isSuccess && (
        <FlatList<Product>
          data={data}
          testID="product-list-flat-list"
          refreshControl={
            <RefreshControl
              refreshing={isRefetchingByUser}
              onRefresh={refetchByUser}
            />
          }
          renderItem={renderItem}
          numColumns={2}
          ItemSeparatorComponent={renderItemSeparator}
          columnWrapperStyle={styles.columnWrapper}
          contentContainerStyle={styles.contentContainerStyle}
          showsVerticalScrollIndicator={false}
          keyExtractor={getKeyExtractor}
          style={COMMON_STYLES.flex}
        />
      )}
    </SafeAreaView>
  );
};

export default ProductListScreen;

const styles = StyleSheet.create({
  contentContainerStyle: {
    flexGrow: 1,
    padding: COMMON_STYLES.screenPadding,
  },
  columnWrapper: {
    justifyContent: "space-between",
  },
});
```

Этот экран отвечает за следующее:

- Отображение товаров с помощью собственного hook react query useGetAllProducts , который мы создали в разделе **_1.4. Загрузка товаров с помощью react-query_**.

- Возможность добавлять товары в корзину и удалять их оттуда с помощью собственного hook zustand useProductActions, который мы разобрали в разделе **_1.7. А вот и zustand: управление товарами в корзине_**.

- Повторная загрузка товаров жестом pull-to-refresh.

- Обновление текста с количеством на иконке корзины в правой части header.

Ниже показано, как работает экран списка товаров:

![](https://cdn-images-1.medium.com/max/2000/1*7wGmDzti0z-d0oPFkKkhCw.gif)

### 2.1. Тестирование экрана списка товаров

В этом разделе мы будем тестировать экран списка товаров. Первые тесты будут такими:

- Сначала должен отображаться индикатор загрузки, даже несмотря на то, что данные замоканы. Флаг isLoading в react-query всё равно ненадолго будет равен true. После загрузки данных isLoading станет false, и индикатор загрузки исчезнет.

- После загрузки данных список товаров должен отображаться правильно. Для проверки этого случая мы используем prop testID компонента ProductListCard.

- Если запрос на получение всех товаров завершился ошибкой, на экране должно появиться сообщение об ошибке. Мы воспользуемся вспомогательной функцией setupGetAllProductsFailedHandler, созданной в разделе **_1.9. Мокирование данных API с помощью MSW_**

### 2.1.1. Тест: сначала должен отображаться индикатор загрузки

```tsx
import { renderHook } from "@testing-library/react-hooks";
import { render, screen } from "@testing-library/react-native";
import React from "react";
import { useGetAllProducts } from "../../api/product";
import { createReactQueryWrapper } from "../../utils/testing";
import ProductListScreen from "../product-list";

const navigateMock = jest.fn();
const navigation = { navigate: navigateMock } as any;
const route = jest.fn() as any;

const component = <ProductListScreen navigation={navigation} route={route} />;

describe("Product list screen", () => {
  it("should display loading indicator initially", async () => {
    // We render the component and expect to see a loading indicator
    render(component, { wrapper: createReactQueryWrapper });
    expect(screen.queryByTestId(`screen-loader`)).toBeTruthy();

    // We render the product list using useGetAllProducts hook and wait until the products are loaded
    const { result, waitFor } = renderHook(() => useGetAllProducts(), {
      wrapper: createReactQueryWrapper,
    });
    await waitFor(() => result.current.isSuccess);

    // We expect the loading indicator to disappear after the products are loaded
    expect(screen.queryByTestId(`screen-loader`)).not.toBeTruthy();
  });
});
```

В начале файла мы импортировали модули, нужные для запуска тестов. Затем создали переменную component, в которой хранится экран списка товаров, чтобы переиспользовать её во всех тестах. Кроме того, поскольку это экран и мы объявили props экрана в разделе **_2. Обзор экрана списка товаров_**, в **_строке 22_** нам также нужно передать обязательные props экрана: navigation и route. Почему мы деструктурировали объект navigation выше, мы вернёмся к этому в следующих тестах.

**Краткий обзор терминов, которые нужно знать, чтобы понимать тесты:**

- [render](https://callstack.github.io/react-native-testing-library/docs/api#render): глубоко рендерит переданный React-элемент и возвращает helpers для запросов к структуре отрендеренных компонентов.

- [screen](https://callstack.github.io/react-native-testing-library/docs/api#screen): хранит результат последнего вызова render, чтобы было проще обращаться к запросам и другим функциям, которые возвращает [render](https://callstack.github.io/react-native-testing-library/docs/api#render).

- [renderHook](https://react-hooks-testing-library.com/reference/api#renderhook) : рендерит тестовый компонент, который при каждом рендере вызывает переданный callback вместе со всеми hooks, которые в нём вызываются.

  > Поскольку главная цель этой статьи показать, как проводить тестирование, а не познакомить с тестовыми библиотеками и их функциями, мы не будем углубляться в детали. В любом случае по ходу статьи будет достаточно примеров их использования.

Тест выше проверяет, отображается ли компонент загрузки экрана в самом начале. Функция render рендерит компонент ProductListScreen, обёрнутый в функцию createReactQueryWrapper. Это простая утилита для создания [QueryClientProvider](https://tanstack.com/query/v4/docs/react/reference/QueryClientProvider) . Функция screen.queryByTestId() проверяет, отображается ли индикатор загрузки на экране.

Функция renderHook используется для тестирования hook useGetAllProducts, который компонент ProductListScreen использует для загрузки данных о товарах. В renderHook передаётся опция wrapper, чтобы обернуть hook useGetAllProducts в функцию createReactQueryWrapper. Переменная result содержит значение, которое возвращает hook useGetAllProducts. Функция waitFor ждёт, пока свойство isSuccess объекта result не станет true, то есть пока данные о товарах не будут успешно загружены.

Вторая часть проверяет, что компонент загрузки экрана больше не отображается после успешной загрузки данных о товарах.

> Мы использовали queryByTestId вместо getByTestId, потому что знаем, что компонент загрузки **не будет виден** после загрузки данных, и getByTestId выбросил бы ошибку.

Если бы мы использовали getByTestId, ошибка могла бы выглядеть так:

![](https://cdn-images-1.medium.com/max/2236/1*l3eXZ10vsIAEedjFSUBQ4w.png)

### 2.1.2. Тест: данные списка товаров должны отображаться правильно

```tsx
import { renderHook } from "@testing-library/react-hooks";
import { render, screen } from "@testing-library/react-native";
import React from "react";
import { useGetAllProducts } from "../../api/product";
import { createReactQueryWrapper } from "../../utils/testing";
import ProductListScreen from "../product-list";

const navigateMock = jest.fn();
const navigation = { navigate: navigateMock } as any;
const route = jest.fn() as any;

const component = <ProductListScreen navigation={navigation} route={route} />;

describe("Product list screen", () => {
  it("should display product list data correctly", async () => {
    // Render the component and wait for it to load
    render(component, { wrapper: createReactQueryWrapper });

    // Check that no product card is rendered before fetching data
    expect(screen.queryByTestId(`product-list-card-1`)).not.toBeTruthy();

    // Fetch the product data
    const { result, waitFor } = renderHook(() => useGetAllProducts(), {
      wrapper: createReactQueryWrapper,
    });

    // Wait for the data to be fetched successfully
    await waitFor(() => result.current.isSuccess);

    // Check that each product card is rendered for each product in the data
    for (const { id } of result.current.data!) {
      expect(screen.queryByTestId(`product-list-card-${id}`)).toBeTruthy();
    }
  });
});
```

Этот тест проверяет, правильно ли экран списка товаров отображает загруженные данные о товарах.

Мы снова ждём успешной загрузки данных, а затем убеждаемся, что данные списка товаров отображаются правильно: проходим циклом по загруженным данным и ожидаем, что для каждого товара существует карточка с testID product-list-card-${id}. Свойство id генерируется динамически на основе ID товара. Если тест падает, значит, элементы списка неправильно отображают данные о товарах.

Обратите внимание, как мы использовали функцию renderItem для рендера элементов списка ниже. Мы берём product.id и объединяем его со строкой product-list-card, чтобы получить динамический testID для компонента ProductListCard. Так мы сможем протестировать все товары вместе с их prop testID.

```tsx
const renderItem = ({ item: product }: ListRenderItemInfo<Product>) => {
  return (
    <ProductListCard
      {...product}
      testID={`product-list-card-${product.id}`}
      basketButtonTestID={`basket-button-${product.id}`}
      isInBasket={
        typeof productsInBasket.find(
          (productInBasket) => productInBasket.product.id === product.id
        ) !== "undefined"
      }
      onAddToBasketPress={onAddToBasketPress(product)}
      onPress={onProductCardPress(product.id)}
    />
  );
};
```

### 2.1.3. Тест: если запрос всех товаров завершился ошибкой, должен отображаться текст ошибки

В этом тесте мы проверяем сценарий, в котором вызов API для загрузки всех товаров завершается ошибкой.

```tsx
import { renderHook } from "@testing-library/react-hooks";
import { render, screen } from "@testing-library/react-native";
import React from "react";
import { setupGetAllProductsFailedHandler } from "../../../__mocks__/msw/handlers";
import { useGetAllProducts } from "../../api/product";
import { createReactQueryWrapper } from "../../utils/testing";
import ProductListScreen from "../product-list";

const navigateMock = jest.fn();
const navigation = { navigate: navigateMock } as any;
const route = jest.fn() as any;

const component = <ProductListScreen navigation={navigation} route={route} />;

describe("Product list screen", () => {
  it("should display error text in case get all products query fails", async () => {
    // Set up the mock handler for GET requests to the /products endpoint that returns an error response
    setupGetAllProductsFailedHandler();

    // Render the ProductListScreen component wrapped in the React Query wrapper
    render(component, { wrapper: createReactQueryWrapper });

    // Set up a mock React hook that calls the useGetAllProducts hook from the API module
    const { result, waitFor } = renderHook(() => useGetAllProducts(), {
      wrapper: createReactQueryWrapper,
    });

    // Wait for the useGetAllProducts hook to throw an error
    await waitFor(() => result.current.isError);

    // Assert that the "An error occurred" text is displayed on the screen
    expect(screen.getByText(`An error occurred`)).toBeTruthy();
  });
});
```

Чтобы имитировать сбой API, мы используем функцию setupGetAllProductsFailedHandler из mock service worker (msw), которую реализовали в разделе **_1.9. Мокирование данных API с помощью MSW_** в строке 38. Затем мы рендерим компонент ProductListScreen функцией render и вызываем hook useGetAllProducts, который загружает данные, через функцию renderHook.

С помощью функции waitFor из @testing-library/react-hooks мы ждём, пока свойство isError объекта result.current не станет true. Так мы убеждаемся, что hook завершил выполнение и вызов API завершился ошибкой. Наконец, мы проверяем, что на экране отображается сообщение об ошибке «An error occurred» (его можно найти в исходном коде экрана списка товаров), с помощью функции getByText из @testing-library/react-native.

### 2.1.4. Тест: при нажатии на первый товар должна вызываться навигация

Мы протестируем следующий фрагмент кода, который на самом деле взят из нашего экрана списка товаров. Этот код обрабатывает нажатие пользователя на любую карточку товара в списке.

```tsx
const onProductCardPress = React.useCallback(
  (productId: number) => () => {
    navigation.navigate(RouteNames.productDetail, { id: productId });
  },
  [navigation]
);

const renderItem = ({ item: product }: ListRenderItemInfo<Product>) => {
  return (
    <ProductListCard
      {...product}
      testID={`product-list-card-${product.id}`}
      basketButtonTestID={`basket-button-${product.id}`}
      isInBasket={
        typeof productsInBasket.find(
          (productInBasket) => productInBasket.product.id === product.id
        ) !== "undefined"
      }
      onAddToBasketPress={onAddToBasketPress(product)}
      onPress={onProductCardPress(product.id)}
    />
  );
};
```

Посмотрим ниже, как можно подойти к его тестированию:

```tsx
import { renderHook } from "@testing-library/react-hooks";
import { fireEvent, render, screen } from "@testing-library/react-native";
import React from "react";
import { useGetAllProducts } from "../../api/product";
import { RouteNames } from "../../navigation/route-names";
import { createReactQueryWrapper } from "../../utils/testing";
import ProductListScreen from "../product-list";

const navigateMock = jest.fn();
const navigation = { navigate: navigateMock } as any;
const route = jest.fn() as any;

const component = <ProductListScreen navigation={navigation} route={route} />;

describe("Product list screen", () => {
  it("should call navigation action on pressing the first product item", async () => {
    // render ProductListScreen component with createReactQueryWrapper as a wrapper
    render(component, { wrapper: createReactQueryWrapper });

    // render hook for useGetAllProducts with createReactQueryWrapper as a wrapper
    const { result, waitFor } = renderHook(() => useGetAllProducts(), {
      wrapper: createReactQueryWrapper,
    });

    // wait for useGetAllProducts to succeed
    await waitFor(() => result.current.isSuccess);

    // find first product item and simulate a press event on it
    const firstProductItem = screen.getByTestId(`product-list-card-1`);
    fireEvent.press(firstProductItem);

    // assert that navigation action was called with correct route name and params
    expect(navigateMock).toHaveBeenCalledWith(RouteNames.productDetail, {
      id: 1,
    });
  });
});
```

В этом фрагменте мы проверяем, вызывается ли навигация при нажатии на товар. Сначала мы рендерим компонент ProductListScreen и ждём успешной загрузки данных, как и в предыдущих тестах. Затем берём первый товар из списка и имитируем нажатие на него с помощью fireEvent.press. Наконец, ожидаем, что функция navigate объекта navigation была вызвана с ожидаемыми параметрами RouteName и productId.

### 2.1.5. Тест: при нажатии на иконку корзины товар должен правильно добавляться и удаляться

Тест ниже проверяет сценарий, в котором пользователь добавляет товар в корзину и удаляет его оттуда, нажимая иконку корзины на карточке товара на экране Product List.

```tsx
import { NavigationContainer } from "@react-navigation/native";
import { renderHook } from "@testing-library/react-hooks";
import { fireEvent, render, screen } from "@testing-library/react-native";
import React from "react";
import { useGetAllProducts } from "../../api/product";
import ProductStack from "../../navigation/product-stack";
import { useProductStore } from "../../store/product";
import { createReactQueryWrapper } from "../../utils/testing";

// We render the whole app stack instead of rendering just the screen
// because we need access to the react-navigation's header, which wouldn't
// be possible if we just rendered the screen.
const rootAppComponent = (
  <NavigationContainer>
    <ProductStack />
  </NavigationContainer>
);

describe("Product list screen", () => {
  it("should add/remove product item correctly on pressing product items basket icon", async () => {
    // We render the entire app stack and use the createReactQueryWrapper as a
    // wrapper for the render function to set up the React Query Provider.
    render(rootAppComponent, {
      wrapper: createReactQueryWrapper,
    });

    // We use the renderHook function to invoke the useGetAllProducts hook which
    // fetches the data.
    const { result, waitFor } = renderHook(() => useGetAllProducts(), {
      wrapper: createReactQueryWrapper,
    });

    // We use the renderHook function to get access to the useProductStore hook
    // which we will use to check that the products in the basket were added/removed correctly.
    const { result: productStore } = renderHook(() => useProductStore(), {
      wrapper: createReactQueryWrapper,
    });

    // We wait for the useGetAllProducts hook to complete fetching the data before proceeding
    // with the test.
    await waitFor(() => result.current.isSuccess);

    // We get the basket button for the first product item using the getByTestId function.
    const firstProductItemBasketButton = screen.getByTestId(`basket-button-1`);

    // We click the basket button for the first product item.
    fireEvent.press(firstProductItemBasketButton);

    // We check that the basket icon quantity text is present using the getByTestId function.
    expect(screen.getByTestId("basket-icon-quantity-text-1")).toBeTruthy();

    // We check that the products in the basket have been added correctly using the productStore.
    expect(productStore.current.productsInBasket).toHaveLength(1);
    expect(productStore.current.productsInBasket[0].quantity).toBe(1);
    expect(productStore.current.productsInBasket[0].product).toMatchObject(
      result.current.data![0]
    );

    // We click the basket button for the first product item again to remove it from the basket.
    fireEvent.press(firstProductItemBasketButton);

    // We check that the basket icon quantity text is not present.
    expect(
      screen.queryByTestId("basket-icon-quantity-text-1")
    ).not.toBeTruthy();

    // We check that the products in the basket have been removed correctly using the productStore.
    expect(productStore.current.productsInBasket).toHaveLength(0);
  });
});
```

Чтобы протестировать работу иконки корзины в header, нам нужно отрендерить весь ProductStack, а не только ProductListScreen. Причина в том, что нам нужен доступ к header экрана Product List, чтобы найти иконку корзины по её test ID. Для этого нужно отрендерить весь ProductStack вместе с NavigationContainer .

После успешной загрузки товаров тест с помощью fireEvent.press имитирует нажатие на иконку корзины у первого товара, и товар добавляется в корзину. Затем мы проверяем, что иконка корзины показывает правильное количество и что товар добавлен в массив productsInBasket в store товаров с правильным количеством и объектом товара.

После этого мы снова имитируем нажатие на иконку корзины, чтобы удалить товар из корзины, и проверяем, что иконка корзины больше не показывает количество, а массив productsInBasket в store товаров пуст.

Итак, этот тест проверяет добавление товара в корзину и его удаление, а также изменение количества при нажатии на иконку корзины на карточке товара на экране Product List и подтверждает, что store товаров правильно управляет товарами и их количеством в корзине.

### 2.1.6. Полный набор тестов экрана списка товаров

Полный набор тестов экрана списка товаров выглядит так:

```tsx
import { NavigationContainer } from "@react-navigation/native";
import { renderHook } from "@testing-library/react-hooks";
import { fireEvent, render, screen } from "@testing-library/react-native";
import React from "react";
import { setupGetAllProductsFailedHandler } from "../../../__mocks__/msw/handlers";
import { useGetAllProducts } from "../../api/product";
import ProductStack from "../../navigation/product-stack";
import { RouteNames } from "../../navigation/route-names";
import { useProductStore } from "../../store/product";
import { createReactQueryWrapper } from "../../utils/testing";
import ProductListScreen from "../product-list";

// We render the whole app stack instead of rendering just the screen
// because we need access to the react-navigation's header, which wouldn't
// be possible if we just rendered the screen.
const rootAppComponent = (
  <NavigationContainer>
    <ProductStack />
  </NavigationContainer>
);
const navigateMock = jest.fn();
const navigation = { navigate: navigateMock } as any;
const route = jest.fn() as any;

const component = <ProductListScreen navigation={navigation} route={route} />;

describe("Product list screen", () => {
  it("should display loading indicator initially", async () => {
    // We render the component and expect to see a loading indicator
    render(component, { wrapper: createReactQueryWrapper });
    expect(screen.queryByTestId(`screen-loader`)).toBeTruthy();

    // We render the product list using useGetAllProducts hook and wait until the products are loaded
    const { result, waitFor } = renderHook(() => useGetAllProducts(), {
      wrapper: createReactQueryWrapper,
    });
    await waitFor(() => result.current.isSuccess);

    // We expect the loading indicator to disappear after the products are loaded
    expect(screen.queryByTestId(`screen-loader`)).not.toBeTruthy();
  });

  it("should display product list data correctly", async () => {
    // Render the component and wait for it to load
    render(component, { wrapper: createReactQueryWrapper });

    // Check that no product card is rendered before fetching data
    expect(screen.queryByTestId(`product-list-card-1`)).not.toBeTruthy();

    // Fetch the product data
    const { result, waitFor } = renderHook(() => useGetAllProducts(), {
      wrapper: createReactQueryWrapper,
    });

    // Wait for the data to be fetched successfully
    await waitFor(() => result.current.isSuccess);

    // Check that each product card is rendered for each product in the data
    for (const { id } of result.current.data!) {
      expect(screen.queryByTestId(`product-list-card-${id}`)).toBeTruthy();
    }
  });

  it("should display error text in case get all products query fails", async () => {
    // Set up the mock handler for GET requests to the /products endpoint that returns an error response
    setupGetAllProductsFailedHandler();

    // Render the ProductListScreen component wrapped in the React Query wrapper
    render(component, { wrapper: createReactQueryWrapper });

    // Set up a mock React hook that calls the useGetAllProducts hook from the API module
    const { result, waitFor } = renderHook(() => useGetAllProducts(), {
      wrapper: createReactQueryWrapper,
    });

    // Wait for the useGetAllProducts hook to throw an error
    await waitFor(() => result.current.isError);

    // Assert that the "An error occurred" text is displayed on the screen
    expect(screen.getByText(`An error occurred`)).toBeTruthy();
  });

  it("should call navigation action on pressing the first product item", async () => {
    // Render the ProductListScreen component along with react-query wrapper
    render(component, { wrapper: createReactQueryWrapper });

    // Render the useGetAllProducts hook with react-query wrapper to fetch data
    const { result, waitFor } = renderHook(() => useGetAllProducts(), {
      wrapper: createReactQueryWrapper,
    });

    // Wait for the data to be fetched
    await waitFor(() => result.current.isSuccess);

    // Find the first product card in the list and simulate a press event on it
    const firstProductItem = screen.getByTestId(`product-list-card-1`);
    fireEvent.press(firstProductItem);

    // Expect that the navigation function is called with the correct route name and params
    expect(navigateMock).toHaveBeenCalledWith(RouteNames.productDetail, {
      id: 1,
    });
  });

  it("should add/remove product item correctly on pressing product items basket icon", async () => {
    // We render the entire app stack and use the createReactQueryWrapper as a
    // wrapper for the render function to set up the React Query Provider.
    render(rootAppComponent, {
      wrapper: createReactQueryWrapper,
    });

    // We use the renderHook function to invoke the useGetAllProducts hook which
    // fetches the data.
    const { result, waitFor } = renderHook(() => useGetAllProducts(), {
      wrapper: createReactQueryWrapper,
    });

    // We use the renderHook function to get access to the useProductStore hook
    // which we will use to check that the products in the basket were added/removed correctly.
    const { result: productStore } = renderHook(() => useProductStore(), {
      wrapper: createReactQueryWrapper,
    });

    // We wait for the useGetAllProducts hook to complete fetching the data before proceeding
    // with the test.
    await waitFor(() => result.current.isSuccess);

    // We get the basket button for the first product item using the getByTestId function.
    const firstProductItemBasketButton = screen.getByTestId(`basket-button-1`);

    // We click the basket button for the first product item.
    fireEvent.press(firstProductItemBasketButton);

    // We check that the basket icon quantity text is present using the getByTestId function.
    expect(screen.getByTestId("basket-icon-quantity-text-1")).toBeTruthy();

    // We check that the products in the basket have been added correctly using the productStore.
    expect(productStore.current.productsInBasket).toHaveLength(1);
    expect(productStore.current.productsInBasket[0].quantity).toBe(1);
    expect(productStore.current.productsInBasket[0].product).toMatchObject(
      result.current.data![0]
    );

    // We click the basket button for the first product item again to remove it from the basket.
    fireEvent.press(firstProductItemBasketButton);

    // We check that the basket icon quantity text is not present.
    expect(
      screen.queryByTestId("basket-icon-quantity-text-1")
    ).not.toBeTruthy();

    // We check that the products in the basket have been removed correctly using the productStore.
    expect(productStore.current.productsInBasket).toHaveLength(0);
  });
});
```

---

### Подводим итоги

В этой статье мы рассмотрели эффективные стратегии тестирования приложений на React Native, которые используют библиотеки React-Query и Zustand, сегодня довольно популярные в приложениях на React и React Native. На примере простого приложения магазина и с подробными примерами мы разобрали процесс тестирования и то, как обеспечить качество кода с помощью тестов. Полный исходный код можно посмотреть по ссылке ниже. Хорошего дня!

[**Ссылка на полный исходный код**](https://github.com/tarikfp/react-native-testing)

### Где опубликовано

**Эта статья также опубликована на:**

- [Medium](https://levelup.gitconnected.com/testing-react-native-with-react-query-and-zustand-d957c2a40b73)

