# Pruebas end-to-end en React Native

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

## Escribe pruebas end-to-end multiplataforma en JavaScript

Escribir pruebas para el código se ha convertido hoy en día en una parte esencial de la programación. Existen distintas metodologías de pruebas de software, como las *pruebas unitarias, las pruebas de integración* y *las pruebas end-to-end*. Este artículo explica cómo aplicar pruebas **_end-to-end_** a una app sencilla de react-native.

Usaremos la librería [**_Detox_**](https://github.com/wix/Detox), desarrollada y mantenida por el equipo de [**_Wix_**](https://github.com/wix).

¡La app es bastante sencilla! Permite a los usuarios dar _me gusta_ a su juego favorito de Nintendo 64. Dicho esto, en realidad hay un único comportamiento que probar en la app: ¡la funcionalidad de _me gusta_!

### Historia de usuario

Enumeremos todas las acciones de usuario posibles para esta funcionalidad:

1. El usuario abre la app.

1. El usuario ve la tarjeta del juego, y la tarjeta tiene un botón de _me gusta_ y un texto con el número _total_ de me gusta. (Para comparar el texto después de la acción del usuario)

1. El usuario pulsa el botón de _me gusta_.

1. El usuario nota que el texto de _me gusta_ ha cambiado. En este caso, el número de me gusta aumenta en uno.

> ADVERTENCIA: En teoría, esta historia de usuario podría considerarse una prueba de integración. Sin embargo, como la app solo se encarga de permitir que los usuarios den me gusta a su juego, se trata como una prueba end-to-end.

### **Código**

Iremos generando el código mientras recorremos las historias de usuario en orden. Cada bloque de código corresponderá al final a una historia de usuario concreta.

1. **El usuario abre la 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. **El usuario ve la tarjeta del juego, y la tarjeta tiene un botón de me gusta y un texto con el número total de me gusta. (Para comparar el texto después de la acción del usuario)**

```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. **El usuario pulsa el botón de me gusta.**

```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. **El usuario nota que el texto de _me gusta_ ha cambiado. En este caso, el número de me gusta aumenta en uno.**

```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**

Veámoslo todo en acción.

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

---

### Conclusión

Este artículo ha cubierto los fundamentos de las pruebas end-to-end en apps de react-native. Para simplificar, la app es lo bastante básica como para mostrar los aspectos fundamentales de las pruebas end-to-end. Desde luego, en aplicaciones reales o en producción puede ser bastante más complicado que esto.

Puedes ver el código fuente final de esta app en el siguiente enlace.

¡Que tengáis todos un día sin bugs!

[Código fuente en GitHub](https://github.com/tarikfp/react-native-n64-voter-app)

### Publicado en

Este artículo también está publicado en:

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

