# React Query ve Zustand ile React Native Testi

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

React Native, hızlı geliştirme döngüsü ve cross-platform uyumluluğu sayesinde mobil uygulama geliştirmek için popüler bir seçim haline geldi. React Native geliştirmeden en iyi şekilde yararlanmak için geliştiriciler, veri çekme ve state yönetimini ele almak üzere sıklıkla React-Query ve Zustand gibi üçüncü parti kütüphanelere yöneliyor. React-Query verinizi çekmek, cache'lemek ve yönetmek için esnek ve verimli bir yol sunarken, Zustand minimalist yaklaşımıyla state yönetimini basit ve güçlü hale getiriyor.

Bu yazıda bu iki kütüphaneyi kullanan React Native uygulamalarını nasıl etkili şekilde test edebileceğimizi inceleyeceğiz. Örnek olarak basit bir mağaza uygulaması kullanacağız ve test sürecini anlamanıza yardımcı olacak kapsamlı ve ayrıntılı örnekler sunacağız. Bu yazının sonunda React Native uygulamalarınızda React-Query ve Zustand'ı nasıl kullanacağınızı ve test edeceğinizi iyi bir şekilde anlamış olacaksınız

### 1: Ortamı kurmak

Mağaza uygulamamızı başlatmak için React Native **_0.71.2_** sürümünü, veri çekme ve state yönetimi için de React-Query (Tanstack query) **_3.39.3_** ve Zustand **_4.3.2_** sürümlerini kullanacağız. Uygulamanın tamamının kaynak kodunu GitHub'da paylaşacağım; doğrudan dalıp çalışırken görmek isterseniz [yazının sonunda paylaşılan bağlantıya erişerek](#8fa3) bunu yapabilirsiniz. Böylece örnekleri takip edebilir ve uygulamanın kodunun tamamını görebilirsiniz.

### 1.1: Store API'sini kurmak

React Native'deki etkili test tekniklerini göstermek için API olarak [https://fakestoreapi.com](https://fakestoreapi.com/) adresini kullanacağız. Mağaza uygulamamız bu API'den bir dizi ürün çekecek ve her ürünün ayrıntılı bir görünümünü sunacak. FakeStoreProduct'ın kullanabileceğimiz başka REST API'leri de olsa, bunları kullanmak karmaşıklığı artırır ve bu yazının asıl amacından uzaklaştırırdı.

Uygulamamız genelinde API'mizle iletişim kurmak için bir axios instance'ı oluşturacağız.

### 1.2: axios instance'ını kurmak

```tsx
import axios from "axios";

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

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

Sonraki adımlarda API'miz için react-query kurulumumuzu oluşturacağız.

### 1.3: Query cache'ini yönetmek için key-factory oluşturmak

key-factory nedir?

[**_TanStack Query, özünde query cache'ini sizin yerinize query key'lerine göre yönetir. Query key'leri en üst seviyede bir Array olmak zorundadır ve tek bir string içeren bir Array kadar basit ya da birçok string ve iç içe nesneden oluşan bir dizi kadar karmaşık olabilir. Query key serialize edilebilir olduğu ve query'nin verisine özgü olduğu sürece onu kullanabilirsiniz!_**](https://tanstack.com/query/latest/docs/react/guides/query-keys)

Uygulamamızın sadeliği cache kullanımını zorunlu kılmasa da, React-Query'nin güçlü cache özelliklerinden yine de yararlanacağız. Bu yüzden aşağıda gösterilecek basit bir key factory oluşturacağız.

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

### 1.4: react-query ile ürünleri çekmek

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

Yukarıda, önceki bölümde oluşturduğumuz query key'i de kullanarak ürünleri çekmek için useGetAllProducts hook'unu oluşturduk.

### 1.5: react-query ile ürün detayını çekmek

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

Önceki hook ile neredeyse aynı; tek farkı, bu sefer useGetProductById hook'unun ürünün detayını id'sine göre çekmek için kullanılacak olması.

### 1.6: Ürün tipi

Ürün nesnesinin nasıl göründüğüne dair bir fikir edinmeyi atlamayalım.

```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: Sahne zustand'ın, sepetteki ürünleri yönetmek

Uygulama, kullanıcıların sepetlerine ürün ekleyip çıkarmasına ve tek tek ürünlerin miktarını ayarlamasına olanak tanıyan temel özellikler içerecek. Ayrıca kullanıcılar sepetin tamamını sıfırlayabilecek. Bu işlevler Zustand ile yönetilecek. Aşağıda implementasyonunu inceleyeceğiz.

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

Kodun ilk kısmı, sepetteki bir ürünün miktarını güncellemek için yardımcı metotlar olan updateProductQuantity, increaseProductQuantityInBasket ve decreaseProductQuantityInBasket adlı üç fonksiyonu tanımlıyor. updateProductQuantity fonksiyonu girdi olarak productsInBasket'e karşılık gelen bir nesne dizisi, bir ürün ID'si ve bir güncelleme tipi (increase ya da decrease) alıyor ve verilen ürünün miktarı güncellenmiş yeni bir productsInBasket dizisi döndürüyor.

ProductStore interface'i ürün store'unun şemasını tanımlıyor. İki property içeriyor:

1. productsInBasket, sepetteki ürünleri temsil eden ProductInBasket nesnelerinden oluşan bir dizi.

1. actions, sepetteki ürünleri yönetmek için fonksiyonlar içeren bir nesne: ürün eklemek, ürün çıkarmak, miktarını artırmak/azaltmak ve sepeti sıfırlamak.

useProductStore hook'u Zustand'daki create fonksiyonu kullanılarak oluşturuluyor. State'i ve aksiyonlarıyla birlikte ürün store'unu döndürüyor.

Geri kalan hook'lar, yani useProductActions, useProductsInBasket, useProductsInBasketCount ve useProductInBasketQuantityById, useProductStore hook'undan türetilen selector'lar. Aksiyonlar ya da favorilere eklenen ürünlerin sayısı gibi ürün store'unun belirli kısımlarına erişim sağlıyorlar.

Öte yandan, useProductsInBasket içinde zustand'dan shallow kullandığımızı belirtmekte fayda var. Bunun sebebi, useProductsInBasket'ten dönecek nesne dizisinin [**_primitive tipler_**](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) olmadığı için yeniden render'a yol açacak olması\*; bu yüzden [shallow eşitlik fonksiyonunu geçerek zustand'a nesnenin yüzeysel (shallow) olarak karşılaştırılmasını istediğimizi söylüyoruz.](https://github.com/pmndrs/zustand#selecting-multiple-state-slices)

### 1.8: Test için gerekli paketleri yüklemek

Artık daha çok önemsediğimiz kısma, teste geçebiliriz. Aşağıdaki paketleri kullanacağız:

- [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, diğer adıyla MSW\*(1.0.0)](https://mswjs.io/)\*

Kısa tutmak ve yazıyı uzatmamak adına jest.config.js ve ts-jest gibi test ortamını yapılandırma süreçlerinin bazılarını atlayacağız.

Test ortamını sonunda nasıl kurduğumuza, yazının sonundaki kaynak kodun tamamının bağlantısından göz atabilirsiniz.

### 1.9: MSW ile API verisini mock'lamak

Uygulamamızı react-query ile etkili şekilde test edebilmek için API'mizi mock'lamamız gerekiyor. Bunun için mock service worker'ı (MSW) kullanacağız.

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

Yukarıdaki kodda gerekli modülleri import edip MSW handler'larını kuruyoruz. Biri tüm ürünleri çekmek, diğeri bir ürünü id'sine göre çekmek için olmak üzere, ikisi de başarılı response döndüren iki mock endpoint oluşturuyoruz. Kapsamlı bir test için bu iki endpoint'e başarısızlık senaryolarını simüle edip test edebileceğimiz hatalı handler'lar da oluşturuyoruz.

Yukarıdaki mock kurulumunu tamamlamak için mswServer nesnesini jest.setup.js içinde kullanmamız gerekiyor. Basitçe mswServer'ı tüm test durumlarından önce başlatmak, her test durumundan sonra handler'ları sıfırlamak ve en sonunda da kapatmak isteyeceğiz.

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

Artık testlerde kullanabilmek için API'mizi mock'ladık. Ama henüz tamamlamadık. zustand için de [sağladıkları dokümantasyonu kullanarak](https://docs.pmnd.rs/zustand/guides/testing) test kurulumu yapmamız gerekiyor. Bu, test durumlarımızda zustand kullanırken [testler arasında state'i sıfırlamamızı](https://docs.pmnd.rs/zustand/guides/testing) sağlayacak.

### 1.10: zustand'ı test için yapılandırmak

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

Buradaki kritik nokta, yukarıdaki dosyayı test ortamımıza göre doğru dizine koymak. jest kullandığımız için bu dosyayı [dokümantasyonda anlatıldığı gibi](https://docs.pmnd.rs/zustand/guides/testing) **mocks**/zustand.js konumuna yerleştirmeliyiz.

(Test) ortamını kurmakla uğraşmaktan şimdiden bunalmış hissediyor olabilirsiniz, yine de ortamımızın iskeletini oluşturdukları için bunları ele almam gerekiyordu.

Bununla birlikte, ürünleri göstermek için ekranımızı oluşturduğumuz bölüme hemen geçelim.

### 2: Ürün listesi ekranına genel bakış

Daha önce de belirttiğimiz gibi, ürünleri göstermek için bir ekranımız olacak. Ürün listesi ekranının kodunun tamamını aşağıda görelim:

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

Bu ekran şunlardan sorumlu:

- **_1.4: react-query ile ürünleri çekmek_** bölümünde oluşturduğumuz custom react query hook'u useGetAllProducts ile ürünleri göstermek.

- Yine **_1.7: Sahne zustand'ın, sepetteki ürünleri yönetmek_** bölümünde ele aldığımız custom zustand hook'u useProductActions ile kullanıcıların sepetlerine ürün ekleyip çıkarmasına izin vermek.

- Pull-to-refresh ile ürünleri yeniden çekmek.

- Header'ın sağındaki sepet ikonunda gösterilen miktar metnini güncellemek.

Ürün listesi ekranının demosu aşağıda:

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

### 2.1: Ürün listesi ekranını test etmek

Bu bölümde ürün listesi ekranı üzerinde testler yapacağız. Gerçekleştirilecek ilk test durumları şunlar:

- Veriyi mock'lamamıza rağmen başlangıçta yükleme göstergesi gösterilmeli. react-query'deki isLoading boolean flag'i yine de kısa bir süre true olacak. Veri çekildikten sonra isLoading false olacak ve loader gösterilmeyecek.

- Veri çekildikten sonra ürün listesi doğru şekilde gösterilmeli. Bu durumu doğrulamak için ProductListCard component'inin testID prop'u kullanılacak.

- Tüm ürünleri getiren query başarısız olursa ekran bir hata mesajı göstermeli. **_1.9: MSW ile API verisini mock'lamak_** bölümünde oluşturulan setupGetAllProductsFailedHandler yardımcısını kullanacağız.

### 2.1.1: Test durumu: Başlangıçta yükleme göstergesini göstermeli

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

Dosyanın en üstünde testlerimizi çalıştırmak için gerekli modülleri import ettik. Ardından ürün listesi ekranımızı saklamak için component adında bir değişken oluşturduk; böylece bu değişkeni test durumlarımız boyunca yeniden kullanabiliriz. Ayrıca bu bir ekran olduğu ve ekran props'larını **_2: Ürün listesi ekranına genel bakış_** bölümünde tanımladığımız için, **_22. satırda_** gerekli ekran props'larını, yani navigation ve route'u da sağlamamız gerekiyor. Yukarıda navigation nesnesini neden destructure ettiğimize ilerleyen test durumlarında geri döneceğiz.

**Test durumlarını anlamak için dikkat etmemiz gereken terimlere kısa bir bakış:**

- [render](https://callstack.github.io/react-native-testing-library/docs/api#render): Verilen React elemanını derinlemesine render eder ve çıktı olan component yapısını sorgulamak için yardımcılar döndürür.

- [screen](https://callstack.github.io/react-native-testing-library/docs/api#screen): [render](https://callstack.github.io/react-native-testing-library/docs/api#render) tarafından döndürülen sorgu ve diğer fonksiyonlara daha kolay erişmek için son render çağrısının değerini tutar.

- [renderHook](https://react-hooks-testing-library.com/reference/api#renderhook) : Her render edildiğinde verilen callback'i, çağırdığı hook'lar dahil, çağıracak bir test component'i render eder.

  > Bu yazının asıl amacı test kütüphanelerine ve fonksiyonlarına bir giriş yapmak değil, testin nasıl yapılacağına dair yol göstermek olduğu için bunların ayrıntılarına girmeyeceğiz. Zaten yazı boyunca kullanımlarını görmek için yeterince örneğimiz olacak.

Yukarıdaki test durumu, başlangıçta ekranda bir ekran loader component'inin gösterilip gösterilmediğini kontrol ediyor. render fonksiyonu, ProductListScreen component'ini [QueryClientProvider](https://tanstack.com/query/v4/docs/react/reference/QueryClientProvider) oluşturmak için kullanılan basit bir yardımcı fonksiyon olan createReactQueryWrapper ile sarılmış şekilde render ediyor. screen.queryByTestId() fonksiyonu ekran loader'ının ekranda gösterilip gösterilmediğini kontrol ediyor.

renderHook fonksiyonu, ProductListScreen component'inde ürün verisini çekmek için kullanılan useGetAllProducts hook'unu test etmek için kullanılıyor. useGetAllProducts hook'unu createReactQueryWrapper fonksiyonuyla sarmak için renderHook fonksiyonuna wrapper seçeneği geçiliyor. result değişkeni, useGetAllProducts hook'unun döndürdüğü değeri içeriyor. Bu sırada waitFor fonksiyonu, result nesnesinin isSuccess property'si true olana, yani ürün verisi başarıyla çekilene kadar bekliyor.

İkinci kısım, ürün verisi başarıyla çekildikten sonra ekran loader component'inin artık gösterilmediğini kontrol ediyor.

> getByTestId yerine queryByTestId kullanmamızın sebebi, veri çekildikten sonra ekran loader component'inin **görünmeyeceğini** bilmemiz; dolayısıyla getByTestId kullanmak bir hata fırlatırdı.

getByTestId kullansaydık karşılaşacağımız hata şu olabilirdi:

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

### 2.1.2: Test durumu: Ürün listesi verisini doğru şekilde göstermeli

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

Bu test kodu, ürün listesi ekranının çekilen ürün verisini doğru şekilde gösterip göstermediğini test ediyor.

Bu sefer de verinin başarıyla çekilmesini bekliyoruz, ardından çekilen veri üzerinde döngü kurup verideki her ürün için testID'si product-list-card-${id} olan bir ürün listesi kartının var olmasını bekleyerek ürün listesi verisinin doğru gösterildiğinden emin oluyoruz. id property'si ürün ID'sine göre dinamik olarak oluşturuluyor. Test başarısız olursa, ürün listesi öğelerinin ürün verisini doğru göstermediği anlamına geliyor.

Aşağıda liste öğelerini render etmek için renderItem fonksiyonunu nasıl kullandığımıza dikkat edin. ProductListCard component'i için dinamik bir testID oluşturmak üzere product.id'yi product-list-card string'iyle birleştiriyoruz. Bu şekilde tüm ürünleri ilgili testID prop'larıyla birlikte test edebileceğiz.

```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: Test durumu: Tüm ürünleri getiren query başarısız olursa hata metni göstermeli

Bu test durumunda tüm ürünleri çeken API çağrısının başarısız olduğu senaryoyu test ediyoruz.

```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 hatasını simüle etmek için mock server worker'daki (msw) setupGetAllProductsFailedHandler fonksiyonunu kullanıyoruz; bunu **_1.9: MSW ile API verisini mock'lamak_** bölümünde 38. satırda yazmıştık. Ardından ProductListScreen component'ini render fonksiyonuyla render ediyor ve veriyi çeken useGetAllProducts hook'unu renderHook fonksiyonuyla çağırıyoruz.

result.current nesnesinin isError property'sinin true olmasını beklemek için @testing-library/react-hooks'taki waitFor fonksiyonunu kullanıyoruz. Bu, hook'un çalışmasını tamamladığından ve API çağrısının başarısız olduğundan emin olmamızı sağlıyor. Son olarak, @testing-library/react-native'deki getByText fonksiyonuyla metnin var olup olmadığını kontrol ederek "An error occurred" hata mesajının ekranda gösterileceğini doğruluyoruz (bunu ürün listesi ekranının kaynak koduna bakarak teyit edebilirsiniz).

### 2.1.4: Test durumu: İlk ürün öğesine basıldığında navigasyon aksiyonunu çağırmalı

Aslında ürün listesi ekranımızdan alınmış olan aşağıdaki kod parçasını test edeceğiz. Bu kod, kullanıcının listedeki herhangi bir ürün kartına basma aksiyonunu ele almaktan sorumlu.

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

Bunu test etmeye nasıl yaklaşabileceğimizi aşağıda görelim:

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

Bu test kodu parçasında, bir ürün öğesine basıldığında navigasyon aksiyonunun çağrılıp çağrılmadığını test ediyoruz. Önce ProductListScreen component'ini render ediyor ve önceki test durumlarında olduğu gibi verinin başarıyla çekilmesini bekliyoruz. Ardından listeden ilk ürün öğesini alıp fireEvent.press ile üzerinde bir basma event'i simüle ediyoruz. Son olarak navigation nesnesinin navigate fonksiyonunun beklenen RouteName ve productId parametreleriyle çağrılmış olmasını bekliyoruz.

### 2.1.5: Test durumu: Ürün öğesinin sepet ikonuna basıldığında ürünü doğru şekilde eklemeli/çıkarmalı

Aşağıdaki test durumu, kullanıcının Ürün Listesi ekranındaki ürün kartının üzerindeki sepet ikonuna basarak sepete ürün ekleyip çıkardığı senaryoyu test ediyor.

```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'daki sepet ikonunun işlevselliğini test etmek için ProductListScreen'e ek olarak ProductStack'in tamamını render etmemiz gerekiyor. Çünkü sepet ikonunu test ID'si ile alabilmek için Ürün Listesi ekranının header'ına erişmemiz gerekiyor. Bu da ProductStack'in tamamının NavigationContainer ile birlikte render edilmesini gerektiriyor.

Ürünleri başarıyla çektikten sonra, ilk ürün öğesindeki sepet ikonuna basmayı simüle etmek için fireEvent.press kullanılıyor; bu da ürünü sepete ekliyor. Ardından sepet ikonunun doğru miktarı gösterdiğini ve ürünün, ürün store'undaki productsInBasket dizisine doğru miktar ve ürün nesnesiyle eklendiğini kontrol ediyoruz.

Bundan sonra ürünü sepetten çıkarmak için sepet ikonuna tekrar basmayı simüle ediyor, sepet ikonunun artık miktarı göstermediğini ve ürün store'undaki productsInBasket dizisinin boş olduğunu kontrol ediyoruz.

Özetle bu test durumu, Ürün Listesi ekranındaki ürün kartının üzerindeki sepet ikonuna basarak sepete ürün ekleme ve çıkarmanın yanı sıra miktarlarını ayarlama işlevselliğini test ediyor ve ürün store'unun sepetteki ürünleri ve miktarlarını doğru şekilde yönettiğini doğruluyor.

### 2.1.6: Ürün listesi ekranının tam test akışı

Ürün listesi ekranının tam test akışı şöyle:

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

---

### Toparlarken

Sonuç olarak bu yazıda, bugünlerde herhangi bir React/React Native uygulamasında oldukça popüler olan React-Query ve Zustand kütüphanelerini kullanan React Native uygulamaları için etkili test stratejilerini inceledik. Örnek olarak basit bir mağaza uygulaması kullanıp kapsamlı ve ayrıntılı örnekler sunarak test sürecini ve testler yazarak kod kalitesinin nasıl güvence altına alınacağını ele aldık. Kaynak kodun tamamına aşağıdaki bağlantıdan göz atabilirsiniz. İyi günler!

[**Kaynak kodun tamamı**](https://github.com/tarikfp/react-native-testing)

### Yayınlandığı yerler

**Bu yazı ayrıca şurada da yayınlandı:**

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

