# Testes end-to-end em React Native

By Tarik Pinarci (https://tarikpinarci.com). Published 2022-11-08. Canonical: https://tarikpinarci.com/pt/blog/end-to-end-testing-in-react-native

## Escreva testes end-to-end multiplataforma em Javascript

Escrever testes para o código se tornou uma parte essencial da programação hoje em dia. Existem diferentes tipos de metodologias de teste de software, como *testes unitários, testes de integração* e *testes end-to-end*. Este artigo mostra como podemos aplicar testes **_end-to-end_** em um app react-native simples.

Vamos usar a biblioteca [**_Detox_**](https://github.com/wix/Detox), desenvolvida e mantida pelo time da [**_Wix_**](https://github.com/wix).

O app é bem simples! Ele permite que os usuários deem _like_ no seu jogo favorito de Nintendo 64. Dito isso, existe de fato um comportamento específico para testar no app: a funcionalidade de _like_!

### User Story

Vamos listar todas as ações que o usuário pode fazer nessa funcionalidade:

1. O usuário abre o app.

1. O usuário vê o card do jogo, e o card tem um botão de _like_ e um texto com o número _total_ de likes. (Para comparar o texto depois da ação do usuário)

1. O usuário toca no botão de _like_.

1. O usuário percebe que o texto de _like_ mudou. Neste caso, o número de likes aumentou em um.

> ATENÇÃO: Na teoria, essa user story pode ser considerada um teste de integração. Mas, como o próprio app só é responsável por permitir que os usuários deem like no seu jogo, ela é tratada como teste end-to-end.

### **Código**

Vamos gerar o nosso código enquanto percorremos as user stories em ordem. Cada bloco de código vai corresponder, no fim, a uma user story específica.

1. **O usuário abre o app.**

```tsx
const detox = require("detox");
const config = require("../package.json").detox;

// before doing any test, ensure the app is launched by the device.
beforeAll(async () => {
  await detox.init(config);
  await device.launchApp();
});
```

2. **O usuário vê o card do jogo, e o card tem um botão de like e um texto com o número total de likes. (Para comparar o texto depois da ação do usuário)**

```tsx
it("Game card has the like text and button are available on the screen", async () => {
  // test if the elements are on the screen
  await expect(element(by.id("game-card-like-text-1"))).toExist();
  await expect(element(by.id("game-card-like-button-1"))).toExist();

  // test game card has the like text available on the screen
  const likeTextAttrs = await element(
    by.id("game-card-like-text-1")
  ).getAttributes();

  await expect(element(by.text(likeTextAttrs.text))).toExist();
});
```

3. **O usuário toca no botão de like.**

```tsx
it("pressing the like button", async () => {
  // Tap to the like button to increase like count
  await element(by.id("game-card-like-button-1")).tap();
});
```

4. **O usuário percebe que o texto de _like_ mudou. Neste caso, o número de likes aumentou em um.**

```tsx
it("pressing the like button of the first game card should increase the like count by one", async () => {
  // get like text(like count) before the like button is "tapped"
  const beforeLikeTextAttrs = await element(
    by.id("game-card-like-text-1")
  ).getAttributes();

  // Tap to the like button to increase like count
  await element(by.id("game-card-like-button-1")).tap();

  // calculate final like text(count)
  const increasedLike = Number(beforeLikeTextAttrs.text) + 1;

  // get updated like text
  const afterLikeText = await element(
    by.id("game-card-like-text-1")
  ).getAttributes();

  // test whether the like text(count) has been increased
  await expect(element(by.text(afterLikeText.text.toString()))).toHaveText(
    increasedLike.toString()
  );
});
```

### **Código completo**

```tsx
// For more info on how to write Detox tests, see the official docs:
// https://github.com/wix/Detox/blob/master/docs/README.md

const { reloadApp } = require("./reload");

describe("Example", () => {
  beforeEach(async () => {
    await reloadApp();
  });

  it("First game card has the like text and button are available on the screen", async () => {
    // tests if the elements are on the screen
    await expect(element(by.id("game-card-like-text-1"))).toExist();
    await expect(element(by.id("game-card-like-button-1"))).toExist();

    // test game card has the like text available on the screen
    const likeTextAttrs = await element(
      by.id("game-card-like-text-1")
    ).getAttributes();

    await expect(element(by.text(likeTextAttrs.text))).toExist();
  });

  it("pressing the like button of the first game card should increase the like count by one", async () => {
    // get like text(like count) before the like button is "tapped"
    const beforeLikeTextAttrs = await element(
      by.id("game-card-like-text-1")
    ).getAttributes();

    // Tap to the like button to increase like count
    await element(by.id("game-card-like-button-1")).tap();

    // calculate final like text(count)
    const increasedLike = Number(beforeLikeTextAttrs.text) + 1;

    // get updated like text
    const afterLikeText = await element(
      by.id("game-card-like-text-1")
    ).getAttributes();

    // test whether the like text(count) has been increased
    await expect(element(by.text(afterLikeText.text.toString()))).toHaveText(
      increasedLike.toString()
    );
  });
});
```

### **Demo**

Vamos ver tudo funcionando.

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

---

### Conclusão

Este artigo cobriu o básico de testes end-to-end em apps react-native. Para manter tudo simples, o app é básico o bastante para demonstrar os aspectos fundamentais dos testes end-to-end. Claro que, em aplicações reais ou de produção, isso pode ser bem mais complicado.

Você pode conferir o código-fonte final deste app no link abaixo.

Tenham todos um dia sem bugs!

[Código-fonte no Github](https://github.com/tarikfp/react-native-n64-voter-app)

### Publicado em

Este artigo também foi publicado em:

- [Medium](https://medium.com/gitconnected/end-to-end-testing-in-react-native-79d23dbf0168)

