# End-to-end тестирование в React Native

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

## Пишем кроссплатформенные end-to-end тесты на Javascript

Написание тестов для кода сегодня стало обязательной частью программирования. Существуют разные подходы к тестированию программного обеспечения: *юнит-тесты, интеграционные тесты* и *end-to-end тесты*. В этой статье я покажу, как применить **_end-to-end_** тестирование к простому приложению на react-native.

Мы будем использовать библиотеку [**_Detox_**](https://github.com/wix/Detox), которую разрабатывает и поддерживает команда [**_Wix_**](https://github.com/wix).

Приложение очень простое! Оно позволяет пользователям ставить _лайк_ любимой игре для Nintendo 64. Поэтому в приложении есть ровно одно поведение, которое нужно протестировать: функция _лайка_!

### Пользовательский сценарий

Перечислим все действия пользователя для этой функции:

1. Пользователь открывает приложение.

1. Пользователь видит карточку игры, а на карточке есть кнопка _лайка_ и текст с _общим_ *количеством лайков*. (Чтобы сравнить текст после действия пользователя)

1. Пользователь нажимает кнопку _лайка_.

1. Пользователь замечает, что текст _лайков_ изменился. В нашем случае количество лайков увеличилось на единицу.

> ОГОВОРКА: теоретически этот пользовательский сценарий можно считать интеграционным тестом. Но поскольку само приложение отвечает только за то, чтобы пользователи могли лайкнуть свою игру, мы рассматриваем его как end-to-end тестирование.

### **Код**

Мы будем писать код, проходя по пользовательским сценариям по порядку. Каждый блок кода в итоге соответствует определённому шагу сценария.

1. **Пользователь открывает приложение.**

```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. **Пользователь видит карточку игры, а на карточке есть кнопка лайка и текст с общим количеством лайков. (Чтобы сравнить текст после действия пользователя)**

```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. **Пользователь нажимает кнопку лайка.**

```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. **Пользователь замечает, что текст _лайков_ изменился. В нашем случае количество лайков увеличилось на единицу.**

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

### **Полный код**

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

### **Демо**

Посмотрим, как всё работает.

![Демо приложения: нажатие на кнопку лайка увеличивает счётчик](https://cdn-images-1.medium.com/max/2000/1*p9YIVHUK5tLqVmMVPI67Tg.gif)

---

### Заключение

В этой статье мы разобрали основы end-to-end тестирования в приложениях на react-native. Ради простоты само приложение достаточно примитивное, чтобы показать базовые аспекты end-to-end тестирования. В реальных, продакшен приложениях всё, конечно, может быть сложнее.

Финальный исходный код приложения можно посмотреть по ссылке ниже.

Всем дня без багов!

[Исходный код на Github](https://github.com/tarikfp/react-native-n64-voter-app)

### Публикации

Эта статья также опубликована на:

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

