DEV Community

Cover image for Setup Detox em aplicações React Native
Davi Borges Seares
Davi Borges Seares

Posted on • Originally published at dev.to

3 2

Setup Detox em aplicações React Native

Em setembro do ano passado a Rocketseat lançou um Code/drops#101 ensinando a configurar e rodar testes no React Native usando detox. Porém o tutorial que é feito lá não contempla o iIOS, apenas o android. Por isso decidir documentar o setup passo a passo para que você consiga de maneira fácil, rodar testes e2e tanto no android quanto no iIOS. Bora?

Repositório com a aplicação no github: codedrop-teste2e

Ambiente

Na raiz do seu terminal, instale o detox-cli globalmente

 npm install -g detox-cli
Enter fullscreen mode Exit fullscreen mode

Na raiz do seu projeto, instale o detox e o jest como dependências de desenvolvimento

 yarn add detox jest -D
Enter fullscreen mode Exit fullscreen mode

Android

1. Na pasta Android > build.gradle

Dentro de repositories, adicione o bloco maven.

allprojects {
    repositories {
                ...
                // adicione apenas o bloco maven abaixo
        maven {
            // Add to detox
            url "$rootDir/../node_modules/detox/Detox-android"
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Na pasta Android > App > build.gradle

Adicione as novas dependências necessárias para rodar os testes no android

android {
    defaultConfig {
                ...
        // Novas dependencias para rodar os testes.
        testBuildType System.getProperty('testBuildType', 'debug')
        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
    }
}

Enter fullscreen mode Exit fullscreen mode

No mesmo arquivo, adicione:

dependencies {
        // Novas dependencias para rodar os testes.
    androidTestImplementation('com.wix:detox:+') { transitive = true }
    androidTestImplementation 'junit:junit:4.12'
}
Enter fullscreen mode Exit fullscreen mode

4. Setup de teste no Android

Agora, vamos criar um arquivo chamado DetoxTest.java no seguinte caminho:
android/app/src/androidTest/java/com/[nome_do_package]/DetoxTest.java

package com.package; // Trocar pelo no do Projeto.

import com.wix.detox.Detox;
import com.wix.detox.config.DetoxConfig;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class DetoxTest {
    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class, false, false);

    @Test
    public void runDetoxTests() {
        DetoxConfig detoxConfig = new DetoxConfig();
        detoxConfig.idlePolicyConfig.masterTimeoutSec = 90;
        detoxConfig.idlePolicyConfig.idleResourceTimeoutSec = 60;
        detoxConfig.rnContextLoadTimeoutSec = (com.package.BuildConfig.DEBUG ? 180 : 60);

        Detox.runTests(mActivityRule, detoxConfig);
    }
}
Enter fullscreen mode Exit fullscreen mode

iOS

Instale o brew na raiz do terminal, então:

brew tap wix/brew
brew install applesimutils
Enter fullscreen mode Exit fullscreen mode

Setup detox

Iniciando com detox

yarn detox init -r jest
Enter fullscreen mode Exit fullscreen mode

Atualizando o arquivo .detoxrc.json

{
  "testRunner": "jest",
  "runnerConfig": "e2e/config.json",
  "configurations": {
    "android.emu.debug": {
      "type": "android.emulator",
      "binaryPath": "android/app/build/outputs/apk/debug/app-debug.apk",
      "build": "cd android && ./gradlew assembleDebug assembleAndroidTest -DtestBuildType=debug && cd ..",
      "device": {
        "avdName": "Pixel_5_API_31" // your avd-name here
      }
    },
    "ios.sim.debug": {
      "type": "ios.simulator",
      "binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/yourProject.app",
      "build": "xcodebuild -workspace ios/yourProject.xcworkspace -scheme yourProject -sdk iphonesimulator -derivedDataPath ios/Build",
      "device": {
        "type": "iPhone 11"
      }
    }
  },
}
Enter fullscreen mode Exit fullscreen mode

Gerando a build para teste

No Android:
yarn detox build -c android.emu.debug

No iOS:
yarn detox build -c ios.sim.debug
Enter fullscreen mode Exit fullscreen mode

Executando testes com Detox

No Android:
yarn detox test -c android.emu.debug

No iOS:
yarn detox test -c ios.sim.debug
Enter fullscreen mode Exit fullscreen mode

🚨 xcode problems 🚨

Caso você tenha um problema no build ios, tente mudar o caminho da pasta build conforme a imagem abaixo.

No menu do xcode acesse files > xcoworkspace settings > Advanced > Custom.

Image description

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more