# Kiểm thử React Native với React Query và Zustand

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

React Native đã trở thành lựa chọn phổ biến để xây dựng ứng dụng mobile nhờ chu kỳ phát triển nhanh và khả năng chạy đa nền tảng. Để tận dụng tối đa React Native, lập trình viên thường dùng thêm các thư viện bên thứ ba như React-Query và Zustand để xử lý việc lấy dữ liệu và quản lý state. React-Query mang lại một cách linh hoạt và hiệu quả để fetch, cache và quản lý dữ liệu, còn Zustand giúp việc quản lý state trở nên đơn giản mà vẫn mạnh mẽ nhờ cách tiếp cận tối giản.

Trong bài viết này, chúng ta sẽ tìm hiểu cách test hiệu quả các ứng dụng React Native dùng hai thư viện này. Chúng ta sẽ lấy một app cửa hàng đơn giản làm ví dụ và đưa ra các ví dụ đầy đủ, chi tiết để bạn hiểu rõ quy trình test. Đọc xong bài này, bạn sẽ nắm khá chắc cách dùng và test React-Query cùng Zustand trong app React Native của mình

### 1. Thiết lập môi trường

Chúng ta sẽ dùng React Native phiên bản **_0.71.2_** để khởi tạo app cửa hàng, cùng React-Query (Tanstack query) phiên bản **_3.39.3_** và Zustand phiên bản **_4.3.2_** để xử lý việc lấy dữ liệu và quản lý state. Tôi sẽ chia sẻ toàn bộ source code của app hoàn chỉnh trên GitHub, nên nếu bạn muốn nhảy vào xem nó chạy thực tế thì có thể [mở đường link được chia sẻ ở cuối bài](#8fa3). Như vậy bạn có thể làm theo các ví dụ và xem toàn bộ code của app.

### 1.1 Thiết lập API cho cửa hàng

Chúng ta sẽ dùng [https://fakestoreapi.com](https://fakestoreapi.com/) làm API để minh họa các kỹ thuật test hiệu quả trong React Native. App cửa hàng sẽ lấy một danh sách sản phẩm từ API này và hiển thị trang chi tiết cho từng sản phẩm. Dù FakeStoreProduct còn có các REST API khác mà ta có thể dùng, làm vậy sẽ tăng độ phức tạp và làm lệch khỏi mục tiêu chính của bài viết.

Để giao tiếp với API trong toàn bộ app, chúng ta sẽ tạo một axios instance.

### 1.2 Thiết lập axios instance

```tsx
import axios from "axios";

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

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

Bước tiếp theo là tạo phần thiết lập react-query cho API của chúng ta.

### 1.3 Tạo key-factory để quản lý cache của query

Key-factory là gì?

[**_Về cốt lõi, TanStack Query quản lý cache của query cho bạn dựa trên query key. Ở cấp cao nhất, query key phải là một Array, và có thể đơn giản như một Array chứa một string duy nhất, hoặc phức tạp như một array gồm nhiều string và object lồng nhau. Miễn là query key có thể serialize được và là duy nhất với dữ liệu của query, bạn đều có thể dùng nó!_**](https://tanstack.com/query/latest/docs/react/guides/query-keys)

Dù app của chúng ta đơn giản đến mức không thật sự cần cache, chúng ta vẫn sẽ tận dụng các tính năng cache mạnh mẽ của React-Query. Vì vậy, chúng ta sẽ tạo một key factory đơn giản như bên dưới.

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

### 1.4 Lấy danh sách sản phẩm bằng 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,
  });
};
```

Ở trên, chúng ta đã tạo hook useGetAllProducts để fetch danh sách sản phẩm, đồng thời dùng query-key đã tạo ở phần trước.

### 1.5 Lấy chi tiết sản phẩm bằng 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,
  });
};
```

Gần giống hook trước, chỉ khác là lần này hook useGetProductById sẽ được dùng để fetch chi tiết của sản phẩm theo id.

### 1.6 Kiểu dữ liệu Product

Đừng bỏ qua phần này, hãy xem object product trông như thế nào.

```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 Đến lượt zustand: quản lý sản phẩm trong giỏ hàng

App sẽ có các tính năng cơ bản cho phép người dùng thêm hoặc xóa sản phẩm khỏi giỏ hàng, cũng như điều chỉnh số lượng của từng sản phẩm. Ngoài ra, người dùng có thể reset toàn bộ giỏ hàng. Các chức năng này sẽ được quản lý bằng Zustand. Bên dưới, chúng ta sẽ xem cách triển khai.

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

Phần đầu của code định nghĩa ba hàm updateProductQuantity, increaseProductQuantityInBasket và decreaseProductQuantityInBasket, là các hàm hỗ trợ để cập nhật số lượng sản phẩm trong giỏ hàng. Hàm updateProductQuantity nhận vào một array các object tương ứng với productsInBasket, một ID sản phẩm và một kiểu cập nhật (tăng hoặc giảm), rồi trả về một array productsInBasket mới với số lượng đã được cập nhật cho sản phẩm đó.

Interface ProductStore định nghĩa schema cho product store. Nó gồm hai thuộc tính:

1. productsInBasket là một array các object ProductInBasket đại diện cho các sản phẩm trong giỏ hàng.

1. actions là một object chứa các hàm để quản lý sản phẩm trong giỏ hàng, bao gồm thêm sản phẩm, xóa sản phẩm, tăng/giảm số lượng và reset giỏ hàng.

Hook useProductStore được tạo bằng hàm create của Zustand. Nó trả về product store cùng state và các action.

Các hook còn lại, useProductActions, useProductsInBasket, useProductsInBasketCount và useProductInBasketQuantityById, là các selector được tạo từ hook useProductStore. Chúng cho phép truy cập vào từng phần cụ thể của product store, chẳng hạn các action hoặc số lượng sản phẩm yêu thích.

Mặt khác, cũng cần nhắc rằng chúng ta đã dùng shallow của zustand trong useProductsInBasket. Lý do là array các object trả về từ useProductsInBasket sẽ gây rerender vì chúng không phải là [**_kiểu nguyên thủy (primitive types)_**](https://developer.mozilla.org/en-US/docs/Glossary/Primitive)\*, vì vậy [chúng ta chỉ cần báo cho zustand rằng muốn so sánh object theo kiểu nông (shallow) bằng cách truyền vào hàm so sánh shallow.](https://github.com/pmndrs/zustand#selecting-multiple-state-slices)

### 1.8 Cài đặt các package cần thiết cho việc test

Giờ chúng ta có thể chuyển sang phần mình quan tâm hơn: test. Chúng ta sẽ dùng các package dưới đây:

- [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 hay còn gọi là MSW\*(1.0.0)](https://mswjs.io/)\*

Để bài viết gọn và không bị kéo dài, chúng ta sẽ bỏ qua một số bước cấu hình môi trường test như jest.config.js và ts-jest .

Bạn cứ thoải mái xem cách chúng tôi thiết lập môi trường test qua đường link source code đầy đủ ở cuối bài.

### 1.9 Mock dữ liệu API bằng MSW

Để test app với react-query một cách hiệu quả, chúng ta cần mock API. Để làm việc này, chúng ta sẽ dùng 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);
```

Trong code ở trên, chúng ta import các module cần thiết và thiết lập các handler của MSW. Chúng ta tạo hai endpoint mock, một để fetch tất cả sản phẩm và một để fetch sản phẩm theo id, cả hai đều trả về response thành công. Để test được kỹ lưỡng, chúng ta cũng tạo các handler thất bại cho hai endpoint này để giả lập và test các tình huống lỗi.

Để hoàn tất phần thiết lập mock ở trên, chúng ta cần dùng object mswServer trong jest.setup.js . Đơn giản là chúng ta muốn khởi tạo mswServer trước mọi test case, reset các handler sau mỗi test case, và cuối cùng thì tắt nó đi.

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

Giờ chúng ta đã mock API để có thể dùng nó trong test. Nhưng vẫn chưa xong. Chúng ta còn cần thiết lập việc test cho zustand [theo tài liệu mà họ cung cấp.](https://docs.pmnd.rs/zustand/guides/testing) Việc này cho phép chúng ta [reset state giữa các test](https://docs.pmnd.rs/zustand/guides/testing) khi dùng zustand trong test case.

### 1.10 Cấu hình zustand cho việc test

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

Điều quan trọng ở đây là đặt file trên vào đúng thư mục tùy theo môi trường test. Vì chúng ta dùng jest, nên cần đặt file này vào **mocks**/zustand.js [như mô tả trong tài liệu](https://docs.pmnd.rs/zustand/guides/testing).

Có thể bạn đã thấy hơi ngợp khi phải xử lý việc thiết lập môi trường (test), nhưng tôi vẫn cần trình bày chúng, vì đây là bộ khung cho môi trường của chúng ta.

Nói vậy thôi, giờ hãy đi thẳng vào phần tạo màn hình hiển thị danh sách sản phẩm.

### 2. Tổng quan màn hình danh sách sản phẩm

Như đã nói, chúng ta sẽ có một màn hình để hiển thị sản phẩm. Hãy xem toàn bộ code của màn hình danh sách sản phẩm bên dưới:

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

Màn hình này chịu trách nhiệm cho các việc sau:

- Hiển thị sản phẩm bằng custom hook react query useGetAllProducts , mà chúng ta đã tạo ở phần **_1.4 Lấy danh sách sản phẩm bằng react-query_**.

- Cho phép người dùng thêm hoặc xóa sản phẩm khỏi giỏ hàng bằng custom hook zustand useProductActions, mà chúng ta cũng đã trình bày ở phần **_1.7 Đến lượt zustand: quản lý sản phẩm trong giỏ hàng_**.

- Fetch lại sản phẩm bằng thao tác kéo để làm mới (pull-to-refresh).

- Cập nhật số lượng hiển thị trên icon giỏ hàng ở góc phải header.

Dưới đây là phần minh họa màn hình danh sách sản phẩm:

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

### 2.1 Test màn hình danh sách sản phẩm

Trong phần này, chúng ta sẽ test màn hình danh sách sản phẩm. Các test case đầu tiên sẽ thực hiện như sau:

- Ban đầu, loading indicator phải được hiển thị, dù chúng ta mock dữ liệu. Cờ boolean isLoading trong react-query vẫn sẽ được đặt là true trong một khoảng thời gian ngắn. Sau khi dữ liệu được fetch xong, isLoading sẽ là false, và loader sẽ không còn hiển thị.

- Danh sách sản phẩm phải được hiển thị chính xác sau khi dữ liệu được fetch xong. Prop testID của component ProductListCard sẽ được dùng để kiểm tra trường hợp này.

- Nếu query lấy tất cả sản phẩm bị lỗi, màn hình phải hiển thị thông báo lỗi. Chúng ta sẽ dùng helper setupGetAllProductsFailedHandler đã tạo ở **_1.9 Mock dữ liệu API bằng MSW_**

### 2.1.1 Test case: Ban đầu phải hiển thị loading indicator

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

Ở đầu file, chúng ta import các module cần thiết để chạy test. Sau đó chúng ta tạo một biến tên component để lưu màn hình danh sách sản phẩm, để có thể dùng lại biến này trong các test case. Hơn nữa, vì đây là một màn hình, và chúng ta đã khai báo screen props ở phần **_2. Tổng quan màn hình danh sách sản phẩm_**, và ở **_dòng 22_**, chúng ta cũng cần truyền vào các screen props bắt buộc là navigation và route. Ở các test case sau, chúng ta sẽ quay lại giải thích vì sao lại destructure object navigation ở trên.

**Điểm qua nhanh các thuật ngữ cần nắm để hiểu các test case:**

- [render](https://callstack.github.io/react-native-testing-library/docs/api#render): Render sâu React element được truyền vào và trả về các helper để query cấu trúc component đầu ra.

- [screen](https://callstack.github.io/react-native-testing-library/docs/api#screen): Giữ giá trị của lần gọi render gần nhất để dễ dàng truy cập các hàm query và những hàm khác mà [render](https://callstack.github.io/react-native-testing-library/docs/api#render) trả về.

- [renderHook](https://react-hooks-testing-library.com/reference/api#renderhook) : Render một test component sẽ gọi callback được truyền vào, bao gồm mọi hook mà callback đó gọi, mỗi lần nó render.

  > Vì mục tiêu chính của bài viết là hướng dẫn cách thực hiện test chứ không phải giới thiệu về các thư viện test và các hàm của chúng, chúng ta sẽ không đi sâu vào chi tiết. Dù sao thì xuyên suốt bài viết cũng sẽ có đủ ví dụ để thấy cách dùng của chúng.

Test case ở trên kiểm tra xem component screen loader có được hiển thị trên màn hình lúc đầu hay không. Hàm render sẽ render component ProductListScreen được bọc trong hàm createReactQueryWrapper, là một hàm tiện ích đơn giản dùng để tạo [QueryClientProvider](https://tanstack.com/query/v4/docs/react/reference/QueryClientProvider) . Hàm screen.queryByTestId() kiểm tra xem screen loader có được hiển thị trên màn hình hay không.

Hàm renderHook được dùng để test hook useGetAllProducts, là hook được dùng trong component ProductListScreen để fetch dữ liệu sản phẩm. Option wrapper được truyền vào hàm renderHook để bọc hook useGetAllProducts trong hàm createReactQueryWrapper. Biến result chứa giá trị mà hook useGetAllProducts trả về. Trong khi đó, hàm waitFor sẽ chờ cho đến khi thuộc tính isSuccess của object result là true, nghĩa là dữ liệu sản phẩm đã được fetch thành công.

Phần thứ hai kiểm tra rằng component screen loader không còn hiển thị sau khi dữ liệu sản phẩm đã được fetch thành công.

> Lý do chúng ta dùng queryByTestId thay vì getByTestId là vì chúng ta biết component screen loader **sẽ không còn hiển thị** sau khi dữ liệu được fetch xong, nên dùng getByTestId sẽ ném ra lỗi.

Nếu dùng getByTestId, lỗi chúng ta gặp phải có thể như sau:

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

### 2.1.2 Test case: Phải hiển thị dữ liệu danh sách sản phẩm chính xác

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

Đoạn code test này kiểm tra xem màn hình danh sách sản phẩm có hiển thị đúng dữ liệu sản phẩm đã fetch hay không.

Lần này, chúng ta lại chờ dữ liệu được fetch thành công, rồi đảm bảo dữ liệu danh sách sản phẩm được hiển thị đúng bằng cách lặp qua dữ liệu đã fetch và expect rằng với mỗi sản phẩm trong dữ liệu đều tồn tại một product list card có testID là product-list-card-${id}. Thuộc tính id được tạo động dựa trên ID của sản phẩm. Nếu test thất bại, nghĩa là các item trong danh sách sản phẩm không hiển thị đúng dữ liệu sản phẩm.

Hãy để ý cách chúng ta dùng hàm renderItem để render các item trong danh sách bên dưới. Chúng ta lặp qua product.id và ghép với string product-list-card để tạo testID động cho component ProductListCard. Bằng cách này, chúng ta có thể test tất cả sản phẩm cùng với prop testID tương ứng của chúng.

```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 case: Phải hiển thị text lỗi khi query lấy tất cả sản phẩm thất bại

Trong test case này, chúng ta test tình huống lời gọi API để fetch tất cả sản phẩm bị thất bại.

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

Để giả lập API bị lỗi, chúng ta dùng hàm setupGetAllProductsFailedHandler từ mock service worker (msw), mà chúng ta đã triển khai ở phần **_1.9 Mock dữ liệu API bằng MSW_** tại dòng 38. Sau đó chúng ta render component ProductListScreen bằng hàm render, và gọi hook useGetAllProducts (hook fetch dữ liệu) bằng hàm renderHook.

Chúng ta dùng hàm waitFor từ @testing-library/react-hooks để chờ thuộc tính isError của object result.current trở thành true. Việc này đảm bảo hook đã chạy xong và lời gọi API đã thất bại. Cuối cùng, chúng ta assert rằng thông báo lỗi “An error occurred” (bạn có thể kiểm tra lại bằng cách xem source code của màn hình danh sách sản phẩm) sẽ được hiển thị trên màn hình, bằng cách kiểm tra text này có xuất hiện hay không với hàm getByText từ @testing-library/react-native.

### 2.1.4 Test case: Phải gọi navigation action khi nhấn vào sản phẩm đầu tiên

Chúng ta sẽ test đoạn code dưới đây, vốn được trích ra từ màn hình danh sách sản phẩm. Đoạn code này chịu trách nhiệm xử lý thao tác nhấn của người dùng vào bất kỳ product list card nào trong danh sách.

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

Hãy xem cách chúng ta tiếp cận việc test nó bên dưới:

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

Trong đoạn code test này, chúng ta kiểm tra xem navigation action có được gọi khi nhấn vào một sản phẩm hay không. Đầu tiên, chúng ta render component ProductListScreen và chờ dữ liệu được fetch thành công giống như các test case trước. Sau đó, chúng ta lấy sản phẩm đầu tiên trong danh sách và giả lập sự kiện nhấn lên nó bằng fireEvent.press. Cuối cùng, chúng ta expect rằng hàm navigate của object navigation đã được gọi với các tham số RouteName và productId như mong đợi.

### 2.1.5 Test case: Phải thêm/xóa sản phẩm chính xác khi nhấn icon giỏ hàng của sản phẩm

Test case dưới đây kiểm tra tình huống người dùng thêm và xóa một sản phẩm khỏi giỏ hàng bằng cách nhấn icon giỏ hàng trên product card ở màn hình 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);
  });
});
```

Để test chức năng của icon giỏ hàng trên header, chúng ta cần render toàn bộ ProductStack chứ không chỉ ProductListScreen. Lý do là chúng ta cần truy cập vào header của màn hình Product List để lấy icon giỏ hàng theo test ID của nó. Điều này đòi hỏi phải render toàn bộ ProductStack, cùng với NavigationContainer .

Sau khi fetch sản phẩm thành công, test dùng fireEvent.press để giả lập việc nhấn icon giỏ hàng trên sản phẩm đầu tiên, thao tác này thêm sản phẩm vào giỏ hàng. Sau đó chúng ta kiểm tra icon giỏ hàng có hiển thị đúng số lượng không, và sản phẩm đã được thêm vào array productsInBasket trong product store với đúng số lượng và đúng object product chưa.

Sau đó, chúng ta giả lập việc nhấn icon giỏ hàng một lần nữa để xóa sản phẩm khỏi giỏ hàng, rồi kiểm tra rằng icon giỏ hàng không còn hiển thị số lượng nữa, và array productsInBasket trong product store đã trống.

Tóm lại, test case này kiểm tra chức năng thêm và xóa sản phẩm khỏi giỏ hàng cũng như điều chỉnh số lượng bằng cách nhấn icon giỏ hàng trên product card ở màn hình Product List, đồng thời xác nhận rằng product store quản lý đúng các sản phẩm và số lượng của chúng trong giỏ hàng.

### 2.1.6 Toàn bộ luồng test của màn hình danh sách sản phẩm

Toàn bộ luồng test của màn hình danh sách sản phẩm như sau:

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

---

### Tổng kết

Tóm lại, bài viết này đã tìm hiểu các chiến lược test hiệu quả cho ứng dụng React Native dùng React-Query và Zustand, hai thư viện khá phổ biến hiện nay trong các ứng dụng React/React Native. Thông qua một app cửa hàng đơn giản làm ví dụ cùng các ví dụ đầy đủ và chi tiết, chúng ta đã đi qua quy trình test và cách đảm bảo chất lượng code bằng việc viết test. Bạn cứ thoải mái xem toàn bộ source code qua đường link bên dưới. Chúc bạn một ngày tốt lành!

[**Link source code đầy đủ**](https://github.com/tarikfp/react-native-testing)

### Đã đăng tại

**Bài viết này cũng được đăng tại:**

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

