# Testando React Native com React Query e Zustand

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

O React Native se tornou uma escolha popular para construir aplicativos mobile graças ao ciclo de desenvolvimento rápido e à compatibilidade multiplataforma. Para aproveitar ao máximo o desenvolvimento com React Native, os desenvolvedores costumam recorrer a bibliotecas de terceiros como React-Query e Zustand para lidar com busca de dados e gerenciamento de estado. O React-Query oferece uma forma flexível e eficiente de buscar, cachear e gerenciar os seus dados, enquanto o Zustand torna o gerenciamento de estado simples e poderoso com a sua abordagem minimalista.

Neste artigo, vamos explorar como testar de forma eficaz aplicações React Native que usam essas duas bibliotecas. Vamos usar um app de loja simples como exemplo e trazer exemplos completos e detalhados para ajudar você a entender o processo de testes. Ao fim deste artigo, você vai ter um bom entendimento de como usar e testar React-Query e Zustand nos seus apps React Native.

### 1. Configurando o ambiente

Vamos usar o React Native na versão **_0.71.2_** para inicializar o nosso app de loja, o React-Query (Tanstack query) na versão **_3.39.3_** e o Zustand na versão **_4.3.2_** para lidar com a busca de dados e o gerenciamento de estado. Vou disponibilizar o código-fonte completo do app no GitHub, então, se você quiser ir direto e ver tudo funcionando, pode [acessar o link compartilhado no fim do artigo](#8fa3). Assim você consegue acompanhar os exemplos e ver o código completo do app.

### 1.1 Configurando a API da loja

Vamos usar a [https://fakestoreapi.com](https://fakestoreapi.com/) como API para demonstrar técnicas eficazes de teste em React Native. O nosso app de loja vai buscar um conjunto de produtos nessa API e mostrar uma visão detalhada de cada produto. Embora a FakeStoreProduct tenha outras APIs REST que poderíamos usar, isso aumentaria a complexidade e desviaria do objetivo principal deste artigo.

Para nos comunicarmos com a API em todo o app, vamos criar uma instância do axios.

### 1.2 Configurando a instância do axios

```tsx
import axios from "axios";

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

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

Os próximos passos serão criar o setup do react-query para a nossa API.

### 1.3 Criando a key-factory para gerenciar o cache das queries

O que é uma key-factory?

[**_Em essência, o TanStack Query gerencia o cache das queries para você com base nas query keys. As query keys precisam ser um Array no nível mais alto, e podem ser tão simples quanto um Array com uma única string ou tão complexas quanto um array com muitas strings e objetos aninhados. Desde que a query key seja serializável e única para os dados da query, você pode usá-la!_**](https://tanstack.com/query/latest/docs/react/guides/query-keys)

Embora a simplicidade do nosso app não exija necessariamente o uso de cache, vamos usar os poderosos recursos de cache do React-Query mesmo assim. Por isso, vamos criar uma key factory simples, mostrada abaixo.

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

### 1.4 Buscando os produtos com 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,
  });
};
```

Acima, criamos o hook useGetAllProducts para buscar os produtos, usando também a query key que criamos na seção anterior.

### 1.5 Buscando o detalhe do produto com 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,
  });
};
```

Quase igual ao hook anterior, só que desta vez o hook useGetProductById será usado para buscar o detalhe do produto pelo seu id.

### 1.6 Tipo do produto

Não vamos pular a parte de entender como é o objeto de produto.

```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 Chegou a vez do zustand: gerenciando os produtos na cesta

O app vai incluir funcionalidades básicas que permitem aos usuários adicionar ou remover produtos da cesta, além de ajustar a quantidade de cada produto. Os usuários também podem esvaziar a cesta inteira. Essas funcionalidades serão gerenciadas com Zustand. Abaixo, vamos ver a implementação.

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

A primeira parte do código define três funções, updateProductQuantity, increaseProductQuantityInBasket e decreaseProductQuantityInBasket, que são métodos auxiliares para atualizar a quantidade de um produto na cesta. A função updateProductQuantity recebe como entrada um array de objetos que corresponde a productsInBasket, um ID de produto e um tipo de atualização (aumentar ou diminuir), e retorna um novo array productsInBasket com a quantidade atualizada do produto informado.

A interface ProductStore define o schema da store de produtos. Ela contém duas propriedades:

1. productsInBasket é um array de objetos ProductInBasket que representa os produtos na cesta.

1. actions é um objeto com funções para gerenciar os produtos na cesta, incluindo adicionar um produto, remover um produto, aumentar ou diminuir a sua quantidade e esvaziar a cesta.

O hook useProductStore é criado com a função create do Zustand. Ele retorna a store de produtos com o seu state e as suas actions.

Os demais hooks, useProductActions, useProductsInBasket, useProductsInBasketCount e useProductInBasketQuantityById, são seletores derivados do hook useProductStore. Eles dão acesso a partes específicas da store de produtos, como as actions ou a contagem de produtos favoritados.

Por outro lado, vale mencionar que usamos o shallow do zustand em useProductsInBasket. Isso porque o array de objetos retornado por useProductsInBasket causaria um re-render, já que não são [**_tipos primitivos_**](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). Por isso, [simplesmente dizemos ao zustand que queremos que o objeto seja comparado de forma rasa, passando a função de igualdade shallow.](https://github.com/pmndrs/zustand#selecting-multiple-state-slices)

### 1.8 Instalando os pacotes necessários para os testes

Agora podemos passar para a parte que mais nos interessa: os testes. Vamos usar os pacotes abaixo:

- [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, também conhecido como MSW (1.0.0)](https://mswjs.io/)

Para ser breve e não alongar o artigo, vamos omitir alguns processos de configuração do ambiente de testes, como o jest.config.js e o ts-jest.

Fique à vontade para ver como acabamos configurando o ambiente de testes no link do código-fonte completo, disponível no fim do artigo.

### 1.9 Mockando os dados da API com MSW

Para testar o app com react-query de forma eficaz, precisamos mockar a nossa API. Para isso, vamos usar o 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);
```

No código acima, importamos os módulos necessários e configuramos os handlers do MSW. Criamos dois endpoints mockados, um para buscar todos os produtos e outro para buscar um produto pelo id, ambos retornando uma resposta de sucesso. Para testar tudo a fundo, também criamos handlers de falha para esses dois endpoints, para simular e testar cenários de erro.

Para completar o setup de mocks acima, precisamos usar o objeto mswServer no nosso jest.setup.js. Basicamente, queremos inicializar o mswServer antes de qualquer caso de teste, resetar os handlers depois de cada caso de teste e, no fim, desligá-lo.

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

Agora mockamos a nossa API para poder usá-la nos testes. Mas ainda não terminamos. Também precisamos configurar os testes do zustand [usando a documentação que eles disponibilizam.](https://docs.pmnd.rs/zustand/guides/testing) Isso vai nos permitir [resetar o state entre os testes](https://docs.pmnd.rs/zustand/guides/testing) ao usar zustand nos nossos casos de teste.

### 1.10 Configurando o zustand para os testes

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

O ponto crucial aqui é colocar o arquivo acima no diretório correto, de acordo com o nosso ambiente de testes. Como usamos jest, devemos colocar esse arquivo em **mocks**/zustand.js, [como descrito na documentação](https://docs.pmnd.rs/zustand/guides/testing).

Talvez você já esteja se sentindo sobrecarregado com toda essa configuração do ambiente (de testes), mas eu precisava cobrir essas partes de qualquer forma, porque elas são o esqueleto do nosso ambiente.

Dito isso, vamos direto para a seção em que criamos a nossa tela de exibição dos produtos.

### 2. Visão geral da tela de lista de produtos

Como mencionamos antes, teremos uma tela para exibir os produtos. Veja abaixo o código completo da tela de lista de produtos:

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

Essa tela é responsável por:

- Exibir os produtos com o hook personalizado do react query, useGetAllProducts, que criamos na seção **_1.4 Buscando os produtos com react-query_**.

- Permitir que os usuários adicionem ou removam produtos da cesta usando o hook personalizado do zustand useProductActions, que também vimos na seção **_1.7 Chegou a vez do zustand: gerenciando os produtos na cesta_**.

- Buscar os produtos de novo com pull-to-refresh.

- Atualizar o texto de quantidade exibido no ícone de cesta no canto direito do header.

Abaixo está a demonstração da tela de lista de produtos:

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

### 2.1 Testando a tela de lista de produtos

Nesta seção, vamos testar a tela de lista de produtos. Os primeiros casos de teste serão os seguintes:

- No início, o indicador de carregamento deve ser exibido, mesmo com os dados mockados. A flag booleana isLoading do react-query ainda fica como true por um curto período. Depois que os dados são buscados, isLoading passa a ser false e o loader deixa de ser exibido.

- A lista de produtos deve ser exibida corretamente depois que os dados forem buscados. A prop testID do componente ProductListCard será usada para verificar esse caso.

- Se a query que busca todos os produtos falhar, a tela deve exibir uma mensagem de erro. Vamos usar o helper setupGetAllProductsFailedHandler criado em **_1.9 Mockando os dados da API com MSW_**.

### 2.1.1 Caso de teste: deve exibir o indicador de carregamento no início

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

No topo do arquivo, importamos os módulos necessários para rodar os testes. Depois, criamos uma variável chamada component para guardar a nossa tela de lista de produtos, para podermos reutilizá-la em todos os casos de teste. Além disso, como é uma tela e declaramos as props da tela na seção **_2. Visão geral da tela de lista de produtos_** e na **_linha 22_**, também precisamos fornecer as props obrigatórias da tela, navigation e route. Nos próximos casos de teste, vamos voltar ao motivo de termos desestruturado o objeto navigation acima.

**Uma rápida revisão da terminologia que precisamos conhecer para entender os casos de teste:**

- [render](https://callstack.github.io/react-native-testing-library/docs/api#render): renderiza profundamente o elemento React informado e retorna helpers para consultar a estrutura dos componentes resultantes.

- [screen](https://callstack.github.io/react-native-testing-library/docs/api#screen): guarda o valor da última chamada de render, para facilitar o acesso às queries e às outras funções retornadas pelo [render](https://callstack.github.io/react-native-testing-library/docs/api#render).

- [renderHook](https://react-hooks-testing-library.com/reference/api#renderhook): renderiza um componente de teste que chama o callback informado, incluindo quaisquer hooks que ele chame, toda vez que renderiza.

  > Como o objetivo principal deste artigo é orientar sobre como fazer testes, e não apresentar as bibliotecas de testes e as suas funções, não vamos entrar em detalhes sobre elas. De qualquer forma, teremos exemplos suficientes ao longo do artigo para ver como são usadas.

O caso de teste acima verifica se um componente de loader da tela é exibido no início. A função render renderiza o componente ProductListScreen envolvido pela função createReactQueryWrapper, uma função utilitária simples usada para criar o [QueryClientProvider](https://tanstack.com/query/v4/docs/react/reference/QueryClientProvider). A função screen.queryByTestId() verifica se o loader está sendo exibido na tela.

A função renderHook é usada para testar o hook useGetAllProducts, que é usado no componente ProductListScreen para buscar os dados dos produtos. A opção wrapper é passada para a função renderHook para envolver o hook useGetAllProducts com a função createReactQueryWrapper. A variável result contém o valor retornado pelo hook useGetAllProducts. Enquanto isso, a função waitFor espera até que a propriedade isSuccess do objeto result seja true, o que significa que os dados dos produtos foram buscados com sucesso.

A segunda parte verifica se o componente de loader deixa de ser exibido depois que os dados dos produtos são buscados com sucesso.

> O motivo de usarmos queryByTestId em vez de getByTestId é que sabemos que o componente de loader **não estará visível** depois que os dados forem buscados. Por isso, usar getByTestId lançaria um erro.

O erro que teríamos ao usar getByTestId poderia ser o seguinte:

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

### 2.1.2 Caso de teste: deve exibir os dados da lista de produtos corretamente

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

Este código de teste verifica se a tela de lista de produtos exibe corretamente os dados de produtos buscados.

Mais uma vez, esperamos os dados serem buscados com sucesso e, depois, garantimos que os dados da lista de produtos são exibidos corretamente, percorrendo os dados buscados e esperando que exista um card de lista de produtos com o testID product-list-card-${id} para cada produto. A propriedade id é gerada dinamicamente com base no ID do produto. Se o teste falhar, significa que os itens da lista de produtos não estão exibindo os dados corretamente.

Repare como usamos a função renderItem para renderizar os itens da lista abaixo. Percorremos product.id e combinamos com a string product-list-card para gerar um testID dinâmico para o componente ProductListCard. Assim, conseguimos testar todos os produtos junto com as suas respectivas props 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 Caso de teste: deve exibir o texto de erro se a query de todos os produtos falhar

Neste caso de teste, testamos o cenário em que a chamada de API para buscar todos os produtos falha.

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

Para simular a falha da API, usamos a função setupGetAllProductsFailedHandler do mock service worker (msw), que implementamos na seção **_1.9 Mockando os dados da API com MSW_**, na linha 38. Depois, renderizamos o componente ProductListScreen com a função render e chamamos, com a função renderHook, o hook useGetAllProducts que busca os dados.

Usamos a função waitFor do @testing-library/react-hooks para esperar a propriedade isError do objeto result.current virar true. Isso garante que o hook terminou de executar e que a chamada de API falhou. Por fim, verificamos que a mensagem de erro "An error occurred" (que você pode conferir no código-fonte da tela de lista de produtos) é exibida na tela, checando se o texto está presente com a função getByText do @testing-library/react-native.

### 2.1.4 Caso de teste: deve chamar a ação de navegação ao tocar no primeiro item de produto

Vamos testar o trecho de código a seguir, que na verdade foi extraído da nossa tela de lista de produtos. Esse código é responsável por tratar o toque do usuário em qualquer card da lista de produtos.

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

Veja abaixo como podemos abordar esse teste:

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

Neste trecho de teste, verificamos se a ação de navegação é chamada quando um item de produto é tocado. Primeiro, renderizamos o componente ProductListScreen e esperamos os dados serem buscados com sucesso, como nos casos de teste anteriores. Depois, pegamos o primeiro item de produto da lista e simulamos um toque nele com fireEvent.press. Por fim, esperamos que a função navigate do objeto navigation tenha sido chamada com os parâmetros RouteName e productId esperados.

### 2.1.5 Caso de teste: deve adicionar e remover o item de produto corretamente ao tocar no ícone de cesta do item

O caso de teste abaixo testa o cenário em que o usuário adiciona e remove um produto da cesta tocando no ícone de cesta do card do produto na tela de lista de produtos.

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

Para testar a funcionalidade do ícone de cesta no header, precisamos renderizar a ProductStack inteira, além da ProductListScreen. Isso porque precisamos acessar o header da tela de lista de produtos para pegar o ícone de cesta pelo seu test ID. Para isso, precisamos ter a ProductStack inteira renderizada, junto com o NavigationContainer.

Depois de buscar os produtos com sucesso, o teste usa fireEvent.press para simular o toque no ícone de cesta do primeiro item de produto, o que adiciona o produto à cesta. Em seguida, verificamos se o ícone de cesta exibe a quantidade correta e se o produto foi adicionado ao array productsInBasket da store de produtos com a quantidade e o objeto de produto corretos.

Depois disso, simulamos um novo toque no ícone de cesta para remover o produto da cesta e verificamos se o ícone de cesta não exibe mais a quantidade e se o array productsInBasket da store de produtos está vazio.

Em resumo, este caso de teste verifica a funcionalidade de adicionar e remover um produto da cesta, além de ajustar as quantidades, tocando no ícone de cesta do card do produto na tela de lista de produtos, e confirma que a store de produtos gerencia corretamente os produtos e as suas quantidades na cesta.

### 2.1.6 Fluxo de testes completo da tela de lista de produtos

O fluxo de testes completo da tela de lista de produtos é o seguinte:

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

---

### Encerrando

Para concluir, este artigo explorou estratégias eficazes de teste para aplicações React Native que usam as bibliotecas React-Query e Zustand, bem populares hoje em dia em qualquer aplicação React/React Native. Usando um app de loja simples como exemplo e trazendo exemplos completos e detalhados, cobrimos o processo de testes e como garantir a qualidade do código por meio da implementação de testes. Fique à vontade para ver o código-fonte completo no link abaixo. Tenha um ótimo dia!

[**Link do código-fonte completo**](https://github.com/tarikfp/react-native-testing)

### Publicado em

**Este artigo também foi publicado em:**

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

