Detox : Gray box end-to-end test automation framework for react-native apps
Tags: reactnative, detox, mobile, testautomation
Published: 2022-06-03 11:03:22

# Pre Requisites :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9hfbbabyr8og0aheichy.png)

### Node.js

Download [Node js](https://nodejs.org/en/download/) or use Homebrew command :

`brew install node`

(Note : Install Node.js v12.0 or above. Use nvm if you need to manage your node versions installed on a single machine)

### Android Studio
[Setting up Android Studio](https://wix.github.io/Detox/docs/introduction/android-dev-env)

Create and Launch Emulators:

`$ANDROID_HOME/tools/bin/avdmanager create avd -n <emulatorname> -d pixel - package "system-images;android-30;google_apis;x86"`
`$ANDROID_HOME/emulator/emulator -verbose @<emulatorname>`

### Xcode

[Setting Up an iOS Development & Testing Environment](https://wix.github.io/Detox/docs/introduction/ios-dev-env)

Create and Launch Simulators:

`xcrun simctl list`
`open -a Simulator - args -CurrentDeviceUDID <UDID>`

### Detox Command Line Tools (detox-cli)

detox-cli should be installed globally, enabling usage of the command line tools outside your npm scripts.

`npm install -g detox-cli`



# Application under Test :

If you already have an application in which detox framework to be set up, Kindly ignore this section. For folks practising hands-on, Please feel free to use this sample react-native feedback app.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pz5tnenthss1h0imk0e7.png)

* Create a react-native project by running the following command:

`npx react-native init <project_name>`

* Install below packages as Dev dependencies :

`npm install -D @react-native-community/checkbox`
`npm install -D react-native-radio-buttons-group`

* Add the below code in your App.js :

[App.js file Github Link](https://github.com/Avinash-Kannan/Detox-MediumBlog-Repo/blob/main/App.js)

* Run your application in Simulator / Emulator :

`npx react-native run-ios`
`npx react-native run-android`



# Setting up detox in react-native project

* Install Detox node module as the first step:

`npm install -D detox`

* Set up a Test Runner (use Jest / Mocha ) :

`npm install -D jest`

* Set up Test-code Scaffolds :

`npx detox init -r jest`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jf7kibqctp13wssnlq6r.png)


# Detox iOS and Android config (.detoxrc.json) :

Configuring detox for iOS includes only updating the ".detoxrc.json" file , where as android requires few additional set up which we will be adding in following steps.

```
"testRunner": "jest",
  "runnerConfig": "e2e/config.json",
  "skipLegacyWorkersInjection": true,
  "apps": {
    "ios": {
      "type": "ios.app",
      "binaryPath": "ios/Build/Products/Debug-iphonesimulator/<YourProject>.app",
      "build": "xcodebuild -workspace ios/<YourProject>.xcworkspace -configuration Debug -scheme <YourProject> -derivedDataPath ios/Build"
      
    },
    "android": {
      "type": "android.apk",
      "binaryPath": "android/app/build/outputs/apk/debug/app-debug.apk",
      "build": "cd android && ./gradlew assembleDebug assembleDebugAndroidTest -DtestBuildType=debug && cd /.."
    }
  },
  "devices": {
    "simulator": {
      "type": "ios.simulator",
      "device": {
        "type": "iPhone 13"
      }
    },
    "emulator": {
      "type": "android.emulator",
      "device": {
        "avdName": "<EmulatorName>"
      }
    }
  },
  "configurations": {
    "ios": {
      "device": "simulator",
      "app": "ios"
    },
    "android": {
      "device": "emulator",
      "app": "android"
    }
  }
```
Under the key "binaryPath", you should provide the path of the .app bundle to use. Under the key "build", specify the xcodebuild command for your project. The 'build' command would output the app bundle in the path specified under 'binaryPath'.


# Additional Set-up for Android :

* Add below code in your root buildscript (i.e. android/build.gradle )
// Note: add the 'allproject' section if it doesn't exist
```
allprojects {
    repositories {
        // ...
        google()
        maven {
            // All of Detox' artifacts are provided via the npm module
            url "$rootDir/../node_modules/detox/Detox-android"
        }
    }
}
```

* Add below code in your app's buildscript (i.e. android/app/build.gradle)
```
dependencies {
    // ...
    androidTestImplementation('com.wix:detox:+')
}
and add this to the defaultConfig subsection
android {
  // ...
  
  defaultConfig {
      // ...
      testBuildType System.getProperty('testBuildType', 'debug')  // This will later be used to control the test apk build type
      testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
  }
}
```
* Create a Detox-Test Class

Detox requires a dummy implementation of a single Android-native test.
1. Add a new file to your project, under this path and name => android/app/src/androidTest/java/com/[your.package]/DetoxTest.java. Double-check that the path is correct!

2. Copy & paste the content of the equivalent file from the [detox example app for RN](https://github.com/wix/Detox/blob/master/examples/demo-react-native/android/app/src/androidTest/java/com/example/DetoxTest.java), into it. Don't forget to change the package name to your project's package name.


# Writing detox test scripts :

* **Locator strategy** :

To eliminate difficulties involved in locating elements in Android/iOS using various Inspectors, it is recommended to define and use testID ( common for both Android/iOS ). In the below video, we will define testID for the elements( app header , checkbox, submit button in sample feedback app) to be automated.

{% embed https://youtu.be/WLCysmZq0Vw %}

* **Adding test cases** :

We will now automate steps to fill and submit feedback.

{% embed https://youtu.be/_hQgLgGk8yI %}

This [test script](https://github.com/Avinash-Kannan/Detox-MediumBlog-Repo/blob/540fbdf2740f2442ecf79ac994e48a7caaacbcb1/e2e/basicTest.e2e.ts) will work smoothly for both android and iOS without any alterations specific to platform.

* **Running tests in Emulator/Simulator **:

In the below video, I have explained the configurations in .detoxrc.json file once again.Used the following commands to build app bundle and run test scripts in Android and iOS.

`detox build -c android`
`detox test -c android`

{% embed https://youtu.be/0vfEBFcHzuU %}

For generating test artifacts, run following command.

`detox test --record-videos all --take-screenshots all -c ios`

* **Exploring API's provided by Detox, Pros and issues**:

This is an optional section explaining additional information on writing effective test scripts using various API's and docs provided by detox.

{% embed https://youtu.be/8N47kieCXpE %}

For Detailed info on below topics :
  * Detox Design Principles 
  * Espresso and EarlGrey - employed by Detox
  * Detox vs Appium

Please visit my [Medium Blog on Detox](https://medium.com/@avinashkannan/detox-gray-box-end-to-end-test-automation-framework-for-react-native-apps-129eb0f19cb0)