# Testowanie React Native z React Query i Zustand

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

React Native stał się popularnym wyborem przy budowaniu aplikacji mobilnych dzięki szybkiemu cyklowi developmentu i wieloplatformowości. Żeby w pełni wykorzystać React Native, deweloperzy często sięgają po zewnętrzne biblioteki, takie jak React-Query i Zustand, do pobierania danych i zarządzania stanem. React-Query daje elastyczny i wydajny sposób na pobieranie, cache'owanie i zarządzanie danymi, a Zustand dzięki minimalistycznemu podejściu sprawia, że zarządzanie stanem jest proste i jednocześnie potężne.

W tym artykule przyjrzymy się, jak skutecznie testować aplikacje React Native, które korzystają z tych dwóch bibliotek. Jako przykładu użyjemy prostej aplikacji sklepu i pokażę obszerne, szczegółowe przykłady, które pomogą zrozumieć proces testowania. Po lekturze będziesz dobrze rozumieć, jak używać i testować React-Query oraz Zustand w swoich aplikacjach React Native

### 1. Przygotowanie środowiska

Do zainicjowania aplikacji sklepu użyjemy React Native w wersji **_0.71.2_**, a do pobierania danych i zarządzania stanem React-Query (Tanstack query) w wersji **_3.39.3_** oraz Zustand w wersji **_4.3.2_**. Pełny kod źródłowy gotowej aplikacji udostępnię na GitHubie, więc jeśli chcesz od razu zobaczyć ją w działaniu, możesz to zrobić, [korzystając z linku udostępnionego na końcu artykułu](#8fa3). Dzięki temu łatwiej będzie śledzić przykłady i zobaczyć pełny kod aplikacji.

### 1.1 Konfiguracja API sklepu

Jako API do pokazania skutecznych technik testowania w React Native użyjemy [https://fakestoreapi.com](https://fakestoreapi.com/). Nasza aplikacja sklepu pobierze z tego API zestaw produktów i pokaże szczegółowy widok każdego z nich. FakeStoreProduct ma też inne REST API, z których moglibyśmy skorzystać, ale zwiększyłoby to złożoność i odciągnęło uwagę od głównego celu artykułu.

Do komunikacji z API w całej aplikacji utworzymy instancję axiosa.

### 1.2 Konfiguracja instancji axiosa

```tsx
import axios from "axios";

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

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

Kolejnym krokiem będzie przygotowanie konfiguracji react-query dla naszego API.

### 1.3 Tworzenie key-factory do zarządzania cache'owaniem queries

Czym jest key-factory?

[**_U podstaw TanStack Query zarządza za ciebie cache'owaniem queries na podstawie query keys. Query keys muszą być tablicą na najwyższym poziomie i mogą być tak proste jak tablica z jednym stringiem albo tak złożone jak tablica wielu stringów i zagnieżdżonych obiektów. Dopóki query key jest serializowalny i unikalny dla danych danego query, możesz go użyć!_**](https://tanstack.com/query/latest/docs/react/guides/query-keys)

Choć nasza prosta aplikacja niekoniecznie potrzebuje cache'owania, i tak skorzystamy z potężnych możliwości cache'owania w React-Query. Utworzymy więc prostą key factory, którą pokazuję poniżej.

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

### 1.4 Pobieranie produktów za pomocą 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,
  });
};
```

Powyżej utworzyliśmy hooka useGetAllProducts do pobierania produktów, korzystając przy tym z query key utworzonego w poprzedniej sekcji.

### 1.5 Pobieranie szczegółów produktu za pomocą 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,
  });
};
```

Prawie to samo co w poprzednim hooku, tylko tym razem hook useGetProductById posłuży do pobierania szczegółów produktu po jego id.

### 1.6 Typ produktu

Nie pomijajmy tego kroku i zobaczmy, jak wygląda obiekt produktu.

```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 Wchodzi zustand: zarządzanie produktami w koszyku

Aplikacja będzie miała podstawowe funkcje, które pozwalają użytkownikom dodawać produkty do koszyka lub je z niego usuwać, a także zmieniać ilość poszczególnych produktów. Dodatkowo użytkownicy mogą wyczyścić cały koszyk. Tymi funkcjami będziemy zarządzać za pomocą Zustand. Poniżej przyjrzymy się implementacji.

```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
  );
```

Pierwsza część kodu definiuje trzy funkcje, updateProductQuantity, increaseProductQuantityInBasket i decreaseProductQuantityInBasket, które są metodami pomocniczymi do aktualizowania ilości produktu w koszyku. Funkcja updateProductQuantity przyjmuje jako argumenty tablicę obiektów odpowiadającą productsInBasket, ID produktu i typ aktualizacji (increase lub decrease), a zwraca nową tablicę productsInBasket ze zaktualizowaną ilością danego produktu.

Interfejs ProductStore definiuje schemat store'a produktów. Zawiera dwie właściwości:

1. productsInBasket to tablica obiektów ProductInBasket reprezentujących produkty w koszyku.

1. actions to obiekt z funkcjami do zarządzania produktami w koszyku, w tym do dodawania produktu, usuwania produktu, zwiększania i zmniejszania jego ilości oraz czyszczenia koszyka.

Hook useProductStore jest tworzony za pomocą funkcji create z Zustand. Zwraca store produktów razem z jego stanem i akcjami.

Pozostałe hooki, useProductActions, useProductsInBasket, useProductsInBasketCount i useProductInBasketQuantityById, to selektory wyprowadzone z hooka useProductStore. Dają dostęp do konkretnych części store'a produktów, na przykład do akcji albo do liczby ulubionych produktów.

Warto też wspomnieć, że w useProductsInBasket użyliśmy shallow z zustand. Wynika to z tego, że tablica obiektów zwracana z useProductsInBasket powodowałaby re-render, bo obiekty nie są [**_typami prostymi_**](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)\*, dlatego [po prostu mówimy zustand, że chcemy porównywać obiekt płytko, przekazując funkcję płytkiego porównania (shallow equality).](https://github.com/pmndrs/zustand#selecting-multiple-state-slices)

### 1.8 Instalacja pakietów potrzebnych do testów

Teraz możemy przejść do części, która interesuje nas bardziej, czyli do testowania. Użyjemy poniższych pakietów:

- [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, czyli MSW\*(1.0.0)](https://mswjs.io/)\*

Dla zwięzłości i żeby nie wydłużać artykułu, pominiemy część kroków konfiguracji środowiska testowego, takich jak jest.config.js i ts-jest .

Śmiało zajrzyj do pełnego kodu źródłowego (link na końcu artykułu), żeby zobaczyć, jak ostatecznie skonfigurowaliśmy środowisko testowe.

### 1.9 Mockowanie danych API za pomocą MSW

Żeby skutecznie testować aplikację z react-query, musimy zamockować nasze API. Użyjemy do tego mock service workera (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);
```

W powyższym kodzie importujemy potrzebne moduły i konfigurujemy handlery MSW. Tworzymy dwa mockowe endpointy: jeden do pobierania wszystkich produktów, drugi do pobierania produktu po id, i oba zwracają poprawną odpowiedź. Żeby testy były dokładne, tworzymy też handlery błędów dla tych dwóch endpointów, aby symulować i testować scenariusze niepowodzenia.

Żeby dokończyć powyższą konfigurację mocków, musimy użyć obiektu mswServer w naszym jest.setup.js . Chcemy po prostu uruchomić mswServer przed wszystkimi przypadkami testowymi, resetować handlery po każdym przypadku testowym, a na końcu go wyłączyć.

```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");
```

Zamockowaliśmy już API, żeby móc go używać w testach. Ale to jeszcze nie wszystko. Musimy też skonfigurować testowanie zustand, [korzystając z dokumentacji, którą udostępniają jego twórcy.](https://docs.pmnd.rs/zustand/guides/testing) Dzięki temu będziemy mogli [resetować stan między testami](https://docs.pmnd.rs/zustand/guides/testing), gdy używamy zustand w przypadkach testowych.

### 1.10 Konfiguracja zustand do testów

```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()));
});
```

Najważniejsze jest tu umieszczenie powyższego pliku we właściwym katalogu, zależnie od środowiska testowego. Ponieważ używamy jest, powinniśmy umieścić ten plik w **mocks**/zustand.js, [tak jak opisano w dokumentacji](https://docs.pmnd.rs/zustand/guides/testing).

Być może czujesz się już przytłoczony całą tą konfiguracją środowiska (testowego), ale i tak musiałem ją omówić, bo to szkielet naszego środowiska.

Przejdźmy więc od razu do sekcji, w której tworzymy ekran wyświetlający produkty.

### 2. Przegląd ekranu listy produktów

Jak wspomnieliśmy wcześniej, będziemy mieli ekran do wyświetlania produktów. Zobaczmy poniżej pełny kod ekranu listy produktów:

```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",
  },
});
```

Ten ekran odpowiada za:

- Wyświetlanie produktów za pomocą własnego hooka react query, useGetAllProducts , który utworzyliśmy w sekcji **_1.4 Pobieranie produktów za pomocą react-query_**.

- Umożliwianie użytkownikom dodawania i usuwania produktów z koszyka za pomocą własnego hooka zustand useProductActions, który omówiliśmy w sekcji **_1.7 Wchodzi zustand: zarządzanie produktami w koszyku_**.

- Ponowne pobieranie produktów za pomocą pull-to-refresh.

- Aktualizowanie tekstu z ilością wyświetlanego przy ikonie koszyka po prawej stronie headera.

Poniżej demonstracja ekranu listy produktów:

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

### 2.1 Testowanie ekranu listy produktów

W tej sekcji przetestujemy ekran listy produktów. Pierwsze przypadki testowe, które wykonamy, są następujące:

- Na początku powinien być wyświetlany wskaźnik ładowania, mimo że mockujemy dane. Flaga isLoading w react-query i tak przez krótki czas będzie ustawiona na true. Po pobraniu danych isLoading zmieni się na false i loader przestanie być wyświetlany.

- Po pobraniu danych lista produktów powinna być wyświetlona poprawnie. Do weryfikacji tego przypadku użyjemy propsa testID komponentu ProductListCard.

- Jeśli query pobierające wszystkie produkty się nie powiedzie, ekran powinien wyświetlić komunikat o błędzie. Użyjemy helpera setupGetAllProductsFailedHandler, który utworzyliśmy w **_1.9 Mockowanie danych API za pomocą MSW_**

### 2.1.1 Przypadek testowy: na początku powinien wyświetlać wskaźnik ładowania

```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();
  });
});
```

Na górze pliku zaimportowaliśmy moduły potrzebne do uruchomienia testów. Następnie utworzyliśmy zmienną component, w której przechowujemy ekran listy produktów, żeby móc jej używać we wszystkich przypadkach testowych. Ponadto, ponieważ to ekran, a propsy ekranu zadeklarowaliśmy w sekcji **_2. Przegląd ekranu listy produktów_**, w **_linii 22_** musimy też przekazać wymagane propsy ekranu, navigation i route. Do tego, dlaczego zdestrukturyzowaliśmy powyżej obiekt navigation, wrócimy w kolejnych przypadkach testowych.

**Krótki przegląd terminologii, którą trzeba znać, żeby zrozumieć przypadki testowe:**

- [render](https://callstack.github.io/react-native-testing-library/docs/api#render): Głęboko renderuje podany element React i zwraca helpery do odpytywania struktury wyrenderowanych komponentów.

- [screen](https://callstack.github.io/react-native-testing-library/docs/api#screen): Przechowuje wartość ostatniego wywołania render, co ułatwia dostęp do zapytań i innych funkcji zwracanych przez [render](https://callstack.github.io/react-native-testing-library/docs/api#render).

- [renderHook](https://react-hooks-testing-library.com/reference/api#renderhook) : Renderuje testowy komponent, który przy każdym renderze wywołuje przekazany callback, łącznie ze wszystkimi hookami, które ten callback wywołuje.

  > Ponieważ głównym celem tego artykułu jest pokazanie, jak prowadzić testy, a nie wprowadzenie do bibliotek testowych i ich funkcji, nie będziemy się w nie zagłębiać. W artykule i tak będzie wystarczająco dużo przykładów, żeby zobaczyć, jak się ich używa.

Powyższy przypadek testowy sprawdza, czy komponent loadera ekranu jest na początku wyświetlany. Funkcja render renderuje komponent ProductListScreen opakowany w funkcję createReactQueryWrapper, czyli prostą funkcję pomocniczą tworzącą [QueryClientProvider](https://tanstack.com/query/v4/docs/react/reference/QueryClientProvider) . Funkcja screen.queryByTestId() sprawdza, czy loader ekranu jest wyświetlany.

Funkcja renderHook służy do testowania hooka useGetAllProducts, którego komponent ProductListScreen używa do pobierania danych produktów. Do renderHook przekazujemy opcję wrapper, żeby opakować hooka useGetAllProducts w funkcję createReactQueryWrapper. Zmienna result zawiera wartość zwracaną przez hooka useGetAllProducts. Funkcja waitFor czeka natomiast, aż właściwość isSuccess obiektu result będzie równa true, co oznacza, że dane produktów zostały poprawnie pobrane.

Druga część sprawdza, czy komponent loadera ekranu przestaje być wyświetlany po poprawnym pobraniu danych produktów.

> Użyliśmy queryByTestId zamiast getByTestId, bo wiemy, że komponent loadera ekranu **nie będzie widoczny** po pobraniu danych, więc getByTestId rzuciłby błąd.

Przy użyciu getByTestId moglibyśmy dostać taki błąd:

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

### 2.1.2 Przypadek testowy: powinien poprawnie wyświetlać dane listy produktów

```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();
    }
  });
});
```

Ten kod testowy sprawdza, czy ekran listy produktów poprawnie wyświetla pobrane dane produktów.

Tym razem również czekamy, aż dane zostaną poprawnie pobrane, a potem upewniamy się, że lista produktów jest wyświetlona poprawnie: przechodzimy w pętli po pobranych danych i oczekujemy, że dla każdego produktu istnieje karta listy produktów z testID product-list-card-${id}. Właściwość id jest generowana dynamicznie na podstawie ID produktu. Jeśli test nie przejdzie, oznacza to, że elementy listy produktów nie wyświetlają danych produktów poprawnie.

Zwróć uwagę, jak poniżej używaliśmy funkcji renderItem do renderowania elementów listy. Przechodzimy przez product.id i łączymy go ze stringiem product-list-card, żeby wygenerować dynamiczny testID dla komponentu ProductListCard. Dzięki temu możemy przetestować wszystkie produkty razem z ich propsem 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 Przypadek testowy: powinien wyświetlać tekst błędu, gdy query pobierające wszystkie produkty się nie powiedzie

W tym przypadku testowym sprawdzamy scenariusz, w którym wywołanie API pobierające wszystkie produkty kończy się błędem.

```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();
  });
});
```

Do symulowania awarii API używamy funkcji setupGetAllProductsFailedHandler z mock service workera (msw), którą zaimplementowaliśmy w sekcji **_1.9 Mockowanie danych API za pomocą MSW_** w linii 38. Następnie renderujemy komponent ProductListScreen za pomocą funkcji render i wywołujemy hooka useGetAllProducts, który pobiera dane, za pomocą funkcji renderHook.

Używamy funkcji waitFor z @testing-library/react-hooks, żeby poczekać, aż właściwość isError obiektu result.current będzie równa true. Daje nam to pewność, że hook zakończył działanie, a wywołanie API się nie powiodło. Na koniec sprawdzamy, że na ekranie wyświetla się komunikat o błędzie „An error occurred” (możesz to zweryfikować w kodzie źródłowym ekranu listy produktów), sprawdzając obecność tego tekstu za pomocą funkcji getByText z @testing-library/react-native.

### 2.1.4 Przypadek testowy: powinien wywołać akcję nawigacji po naciśnięciu pierwszego produktu

Przetestujemy poniższy fragment kodu, który w rzeczywistości pochodzi z ekranu listy produktów. Ten kod obsługuje naciśnięcie przez użytkownika dowolnej karty produktu na liście.

```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)}
    />
  );
};
```

Zobaczmy poniżej, jak możemy podejść do jego testowania:

```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,
    });
  });
});
```

W tym fragmencie kodu testowego sprawdzamy, czy akcja nawigacji zostaje wywołana po naciśnięciu produktu. Najpierw renderujemy komponent ProductListScreen i czekamy na poprawne pobranie danych, tak jak w poprzednich przypadkach testowych. Potem pobieramy pierwszy produkt z listy i symulujemy jego naciśnięcie za pomocą fireEvent.press. Na koniec oczekujemy, że funkcja navigate obiektu navigation została wywołana z oczekiwanymi parametrami RouteName i productId.

### 2.1.5 Przypadek testowy: powinien poprawnie dodawać i usuwać produkt po naciśnięciu ikony koszyka na produkcie

Poniższy przypadek testowy sprawdza scenariusz, w którym użytkownik dodaje produkt do koszyka i usuwa go z niego, naciskając ikonę koszyka na karcie produktu na ekranie 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);
  });
});
```

Żeby przetestować działanie ikony koszyka w headerze, oprócz ProductListScreen musimy wyrenderować cały ProductStack. Potrzebujemy bowiem dostępu do headera ekranu Product List, żeby pobrać ikonę koszyka po jej test ID. Wymaga to wyrenderowania całego ProductStack razem z NavigationContainer .

Gdy produkty zostaną poprawnie pobrane, test używa fireEvent.press, żeby zasymulować naciśnięcie ikony koszyka na pierwszym produkcie, co dodaje produkt do koszyka. Następnie sprawdzamy, czy ikona koszyka wyświetla poprawną ilość oraz czy produkt został dodany do tablicy productsInBasket w store produktów z poprawną ilością i obiektem produktu.

Potem symulujemy ponowne naciśnięcie ikony koszyka, żeby usunąć produkt z koszyka, i sprawdzamy, czy ikona koszyka nie wyświetla już ilości oraz czy tablica productsInBasket w store produktów jest pusta.

Podsumowując, ten przypadek testowy sprawdza dodawanie i usuwanie produktu z koszyka oraz zmianę ilości po naciśnięciu ikony koszyka na karcie produktu na ekranie Product List, a także potwierdza, że store produktów poprawnie zarządza produktami i ich ilościami w koszyku.

### 2.1.6 Pełny przebieg testów ekranu listy produktów

Pełny przebieg testów ekranu listy produktów wygląda następująco:

```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);
  });
});
```

---

### Podsumowanie

Ten artykuł omówił skuteczne strategie testowania aplikacji React Native korzystających z bibliotek React-Query i Zustand, które są obecnie bardzo popularne w aplikacjach React i React Native. Na przykładzie prostej aplikacji sklepu i obszernych, szczegółowych przykładów omówiliśmy proces testowania i to, jak dbać o jakość kodu dzięki testom. Pełny kod źródłowy znajdziesz pod linkiem poniżej. Miłego dnia!

[**Link do pełnego kodu źródłowego**](https://github.com/tarikfp/react-native-testing)

### Opublikowano również

**Ten artykuł został opublikowany także tutaj:**

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

