### Install and Start with npm Source: https://wix.github.io/Detox/docs/contributing/documentation Use this command to install dependencies and start the local development server for the documentation site using npm. ```bash cd website npm install npm start ``` -------------------------------- ### Install and Start with pnpm Source: https://wix.github.io/Detox/docs/contributing/documentation Use this command to install dependencies and start the local development server for the documentation site using pnpm. ```bash cd website pnpm install pnpm start ``` -------------------------------- ### Install and Start with Yarn Source: https://wix.github.io/Detox/docs/contributing/documentation Use this command to install dependencies and start the local development server for the documentation site using Yarn. ```bash cd website yarn install yarn start ``` -------------------------------- ### Wrapping Global Setup Source: https://wix.github.io/Detox/docs/guide/migration Example of how to combine custom global setup with Detox's required setup. ```javascript module.exports = async () => { await require('detox/runners/jest/index').globalSetup(); await yourGlobalSetupFunction(); }; ``` -------------------------------- ### Install an Application Source: https://wix.github.io/Detox/docs/api/device Installs an application from a specified file path. ```javascript await device.installApp('path/to/other/app'); ``` -------------------------------- ### Forward Arguments to Start Script Source: https://wix.github.io/Detox/docs/cli/start Pass additional arguments to the app's 'start' script by using '--' followed by the arguments. This example forwards the port number. ```bash detox start -c yourConfiguration -- --port 8082 ``` -------------------------------- ### Run Detox Start with Default Configuration Source: https://wix.github.io/Detox/docs/cli/start Use this command when you have only one configuration defined in your Detox setup. Detox will automatically select it. ```bash detox start ``` -------------------------------- ### device.installApp() Source: https://wix.github.io/Detox/docs/api/device Installs an application. By default, it installs the app defined in the current configuration. It can also install another app by specifying its path. ```APIDOC ## device.installApp() ### Description Installs the application. By default, `installApp()` with no parameters will install the app file defined in the current `configuration`. To install another app, specify its path. ### Method `device.installApp` ### Endpoint N/A ### Parameters #### Path Parameters - **appPath** (string) - Optional - The path to the application file to install. If not provided, the app defined in the current configuration is installed. ### Request Example ```javascript // Install the default app await device.installApp(); // Install another app await device.installApp('path/to/other/app'); ``` ### Response N/A ### Notes For app state reset operations, consider using `device.resetAppState()` which is more efficient than uninstall/install cycles. ``` -------------------------------- ### Custom Global Setup Wrapper Source: https://wix.github.io/Detox/docs/config/testRunner Pattern for wrapping the default Detox global setup with additional custom logic. ```javascript module.exports = async () => { await require('detox/runners/jest').globalSetup(); await yourGlobalSetupFunction(); }; ``` -------------------------------- ### Handle Jest setup timeout errors Source: https://wix.github.io/Detox/docs/config/testRunner Example of the error output when the Detox environment setup exceeds the configured setupTimeout. ```text FAIL e2e/starter.test.js ● Test suite failed to run Exceeded timeout of 120000ms while setting up Detox environment ``` -------------------------------- ### Configure Jest Global Setup and Teardown Source: https://wix.github.io/Detox/docs/api/internals Example of a Jest configuration file specifying global setup, global teardown, and reporters. Ensure paths are correctly set for your project. ```javascript module.exports = async function () { return { globalSetup: '/path/to/globalSetup.js', globalTeardown: '/path/to/globalTeardown.js', reporters: ['/path/to/reporter.js'], /* ... jest config ... */ }; }; ``` -------------------------------- ### Example: Handle URL Successfully on Launch Source: https://wix.github.io/Detox/docs/guide/mocking-open-with-url This example demonstrates testing deep link handling by launching the app with a URL and asserting that a specific UI element becomes visible. ```javascript describe('launch app from URL', () => { it('should handle URL successfully', async () => { await device.launchApp({ newInstance: true, url: 'scheme://some.url', sourceApp: 'com.apple.mobilesafari' }); await expect(element(by.text('a label'))).toBeVisible(); }); }); ``` -------------------------------- ### Install Packages via Package Managers Source: https://wix.github.io/Detox/docs/demo Commands to install a dummy package using npm, Yarn, or pnpm. ```bash npm install "dummy_package" --save ``` ```bash yarn add "dummy_package" ``` ```bash pnpm add "dummy_package" ``` -------------------------------- ### detox start Source: https://wix.github.io/Detox/docs/cli/start Runs the start command of the app (or apps) from the specified configuration. ```APIDOC ## detox start ### Description Runs the `start` command of the app (or apps) from the specified configuration. ### Method CLI Command ### Endpoint N/A (CLI Command) ### Parameters #### Options - **-C, --config-path ``** (string) - Optional - Specify Detox config file path. If not supplied, Detox searches for .detoxrc[.js] or "detox" section in package.json. - **-c, --configuration ``** (string) - Optional - Select a local configuration from your defined configurations to extract the app "start" scripts from it. If not supplied, and there’s only one configuration, Detox will default to it. - **-f, --force** (boolean) - Optional - Ignore errors from the "start" scripts and continue. - **--help** (boolean) - Optional - Show help ### Request Example ``` detox start ``` ``` detox start --configuration yourConfiguration ``` ``` detox start -c yourConfiguration -- --port 8082 ``` ``` detox start -c yourConfiguration --force ``` ### Response #### Success Response (Output will vary based on the app's start scripts and configuration) #### Response Example (No specific response example provided in the documentation) ``` -------------------------------- ### Detox Configuration Example Source: https://wix.github.io/Detox/docs/guide/migration Detox has normalized its configuration format. This example shows the separation of devices and apps, with the new format being the recommended option. ```json { "apps": { "ios": { "type": "ios", "binaryPath": "path/to/your/app.app", "build": "xcodebuild -..." } }, "devices": { "ios": { "type": "ios", "device": { "type": "simulator" } } }, "configurations": { "ios": { "device": "ios", "app": "ios" } } } ``` -------------------------------- ### Detox Initialization Output Source: https://wix.github.io/Detox/docs/introduction/project-setup Example output showing the files created by the detox init command. ```text Created a file at path: .detoxrc.js Created a file at path: e2e/jest.config.js Created a file at path: e2e/starter.test.js ``` -------------------------------- ### Run Detox Start with Specific Configuration Source: https://wix.github.io/Detox/docs/cli/start Specify a particular configuration to use for starting the app. This is useful when multiple configurations are defined. Use the long or short alias for the --configuration option. ```bash detox start --configuration yourConfiguration ``` ```bash detox start -c yourConfiguration ``` -------------------------------- ### init Source: https://wix.github.io/Detox/docs/api/internals Initializes the Detox context, resolves configuration, and starts necessary services. ```APIDOC ## init([options]) ### Description Initializes the primary or secondary Detox context, starts the logger, IPC server, and installs the worker if required. ### Parameters #### Request Body - **options** (object) - Optional - Configuration object. - **cwd** (string) - Optional - Current working directory. - **argv** (map) - Optional - CLI arguments. - **testRunnerArgv** (map) - Optional - Arguments forwarded to the test runner. - **override** (Partial) - Optional - Ad-hoc adjustments to merge with config. - **global** (object) - Optional - Custom global scope reference. - **workerId** (string | null) - Optional - Unique ID for the worker. ### Response - **Promise** - Returns a promise that resolves when initialization is complete. ``` -------------------------------- ### Example ADB Devices Output Source: https://wix.github.io/Detox/docs/introduction/project-setup Sample output showing connected Android devices. ```text List of devices attached 2F6315NVPH device ``` -------------------------------- ### Install TypeScript with pnpm Source: https://wix.github.io/Detox/docs/guide/typescript Install TypeScript as a development dependency and initialize its configuration file using pnpm. ```bash pnpm add --save-dev typescript tsc --init ``` -------------------------------- ### Install TypeScript with Yarn Source: https://wix.github.io/Detox/docs/guide/typescript Install TypeScript as a development dependency and initialize its configuration file using Yarn. ```bash yarn add --dev typescript tsc --init ``` -------------------------------- ### Install TypeScript with npm Source: https://wix.github.io/Detox/docs/guide/typescript Install TypeScript as a development dependency and initialize its configuration file using npm. ```bash npm install --save-dev typescript tsc --init ``` -------------------------------- ### Example Module to Mock Source: https://wix.github.io/Detox/docs/guide/mocking This is an example of a configuration module that might be used in a React Native application. ```javascript // src/config.js export const SERVER_URL = 'https://production.mycompany.name/api'; export const FETCH_TIMEOUT = 60000; ``` -------------------------------- ### Detox Configuration Example (detox.config.js) Source: https://wix.github.io/Detox/docs/api/internals Example of a `detox.config.js` file demonstrating how to set up app, device, and configuration details. It shows conditional `maxWorkers` based on environment variables. ```javascript /** @type {Detox.DetoxConfig} */ module.exports = { apps: { /* ... */ }, devices: { /* ... */ }, configurations: { 'ios.sim.release': { app: 'ios.release', device: 'iphone', testRunner: { args: { maxWorkers: process.env.CI === 'true' ? 3 : undefined, }, }, }, 'android.emu.release': { app: 'android.release', device: 'nexus', testRunner: { args: { maxWorkers: process.env.CI === 'true' ? 2 : undefined, }, }, }, }, }; ``` -------------------------------- ### Install Detox Source: https://wix.github.io/Detox/docs/introduction/project-setup Install the Detox package as a development dependency. ```bash npm install detox --save-dev ``` ```bash yarn add detox --dev ``` ```bash pnpm add detox --save-dev ``` -------------------------------- ### Configure testRunner arguments Source: https://wix.github.io/Detox/docs/config/testRunner Example of mapping configuration objects to the final spawned command. ```json { "testRunner": { "args": { "$0": "nyc jest", "bail": true, "config": "e2e/jest.config.js", "_": ["e2e/sanity-tests"] } } } ``` ```bash nyc jest --bail --config e2e/jest.config.js e2e/sanity-tests ``` -------------------------------- ### Example Android AVD List Output Source: https://wix.github.io/Detox/docs/introduction/project-setup Sample output showing available Android virtual devices. ```text Pixel_3a_API_30_x86 Pixel_API_30 ``` -------------------------------- ### Initialize Pilot with PromptHandler Source: https://wix.github.io/Detox/docs/pilot/testing-with-pilot Initialize Pilot with your custom PromptHandler before running tests. This setup is typically performed in a `beforeAll` hook or a dedicated setup file. ```javascript const {pilot} = require('detox/index'); const OpenAIPromptHandler = require('./OpenAIPromptHandler'); beforeAll(() => { const promptHandler = new OpenAIPromptHandler('YOUR_OPENAI_API_KEY'); pilot.init(promptHandler); }); ``` -------------------------------- ### Install Detox CLI Source: https://wix.github.io/Detox/docs/cli/overview Install the Detox CLI globally using npm to enable command-line access. ```bash npm install detox-cli --global ``` -------------------------------- ### Install Jest Source: https://wix.github.io/Detox/docs/introduction/project-setup Install the required version of Jest as a development dependency. ```bash npm install "jest@^29" --save-dev ``` ```bash yarn add "jest@^29" --dev ``` ```bash pnpm add "jest@^29" --save-dev ``` -------------------------------- ### Install Jest Test Runner Source: https://wix.github.io/Detox/docs/introduction/project-setup Install Jest as the test runner for the project. ```bash npm install jest --save-dev ``` ```bash yarn add jest --dev ``` ```bash pnpm add jest --save-dev ``` -------------------------------- ### Implement Jest Global Setup Handler Source: https://wix.github.io/Detox/docs/api/internals A basic structure for a Jest global setup handler. This code executes before any tests are run. ```javascript module.exports = async function () { // ... global setup code ... }; ``` -------------------------------- ### Platform-Specific App Configuration Examples Source: https://wix.github.io/Detox/docs/config/apps Basic configuration structures for iOS and Android application targets. ```json { "type": "ios.app", "binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/example.app", "build": "xcodebuild -project ios/example.xcodeproj -scheme example -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build" } ``` ```json { "type": "android.apk", "binaryPath": "path/to/myApp.apk", "build": "cd android && ./gradlew …" } ``` -------------------------------- ### PuppeteerDeviceAllocation Example Source: https://wix.github.io/Detox/docs/guide/migration This example demonstrates how to implement a custom device allocation class for Puppeteer. It shows the structure for allocating and freeing devices, returning an allocation cookie. ```javascript class PuppeteerDeviceAllocation { async allocate() { // ... implementation to acquire a free device return new PuppeteerAllocCookie(/* ... */); } async free() { // ... implementation to release the device } } ``` -------------------------------- ### Execute Command Line Operations Source: https://wix.github.io/Detox/docs/demo Example commands for executing system-level tasks. ```bash $ANDACISUS_SED_EGET/rhoncus/tempus -augue-mollis ``` ```bash $ANDACISUS_SED_EGET/rhoncus/tempus -augue-mollis ``` -------------------------------- ### Full WebView Interaction Test Example Source: https://wix.github.io/Detox/docs/guide/testing-webviews A complete example demonstrating a login flow within a WebView. It includes asserting initial state, filling form fields, tapping a button, and asserting the final state after login. ```javascript it('should login successfully', async () => { // Assert the welcome message is not visible before login await expect(web.element(by.web.id('welcome_message'))).not.toExist(); // Fill username and password await web.element(by.web.id('username')).typeText('John Doe'); await web.element(by.web.id('password')).typeText('123456789'); // Press the login button await web.element(by.web.id('login')).tap(); // Assert the login was successful await expect(web.element(by.web.id('welcome_message'))).toHaveText('Welcome, John Doe!'); }); ``` -------------------------------- ### Example Test Output Source: https://wix.github.io/Detox/docs/guide/genymotion-saas Sample output showing the allocated Genymotion instance and browser access link. ```text Allocating Genymotion-Cloud instance Detox.62dfc57b-3201-c861-29bb-8f31f60a8d39.w1 for testing. To access it via a browser, go to: https://cloud.geny.io/instance/8fc62d21-3de0-4ed8-bf18-e69b90246dc5 ``` -------------------------------- ### Example iOS Device List Output Source: https://wix.github.io/Detox/docs/introduction/project-setup Sample output showing available iOS device types. ```text == Device Types == iPhone 4s (com.apple.CoreSimulator.SimDeviceType.iPhone-4s) iPhone 5 (com.apple.CoreSimulator.SimDeviceType.iPhone-5) … iPhone SE (2nd generation) (com.apple.CoreSimulator.SimDeviceType.iPhone-SE--2nd-generation-) iPhone 12 mini (com.apple.CoreSimulator.SimDeviceType.iPhone-12-mini) iPhone 15 (com.apple.CoreSimulator.SimDeviceType.iPhone-15) iPhone 15 Pro (com.apple.CoreSimulator.SimDeviceType.iPhone-15-Pro) … ``` -------------------------------- ### Jest Config Example (`e2e/jest.config.js`) Source: https://wix.github.io/Detox/docs/config/testRunner An example of a Jest configuration file generated by `detox init`, demonstrating essential Detox-specific settings. ```APIDOC ## Jest Config (`e2e/jest.config.js`) ### Description This file configures Jest for Detox projects, setting up essential properties for test execution, environment, and reporting. ### Properties Explained: 1. **`rootDir` and `testMatch`**: Enforce conventions for test file location (`e2e` folder) and naming (`.test.js` extension). 2. **`testTimeout`**: Overrides the default Jest timeout (5 seconds) to a more suitable value for end-to-end tests (e.g., 120000ms). 3. **`maxWorkers`**: Prevents over-allocation of mobile devices by Jest. It's recommended to set this to 1 to avoid spawning too many devices. Can be overridden via command-line arguments (`--maxWorkers `). * Example for CI environments: ```javascript maxWorkers: process.env.CI ? 2 : 1, ``` 4. **`globalSetup`**: Essential for integrating with Detox Internals API. Allows for additional custom setup logic. * Example with custom setup: ```javascript module.exports = async () => { await require('detox/runners/jest').globalSetup(); await yourGlobalSetupFunction(); }; ``` 5. **`globalTeardown`**: Essential for integrating with Detox Internals API. Allows for additional custom teardown logic. * Example with custom teardown: ```javascript module.exports = async () => { try { await yourGlobalTeardownFunction(); } finally { await require('detox/runners/jest').globalTeardown(); } }; ``` 6. **`reporters`**: Must include a reporter from Detox to ensure compatibility with Detox upgrades. 7. **`testEnvironment`**: The core of Detox-Jest integration. Allows for custom environment extensions. * Example custom environment (`e2e/testEnvironment.js`): ```javascript const { DetoxCircusEnvironment } = require('detox/runners/jest'); class CustomDetoxEnvironment extends DetoxCircusEnvironment { constructor(config, context) { super(config, context); // custom code } async setup(config, context) { await super.setup(config, context); // custom code } async handleTestEvent(event, state) { await super.handleTestEvent(event, state); // custom code } async teardown(config, context) { try { // custom code } finally { await super.teardown(config, context); } } } module.exports = CustomDetoxEnvironment; ``` 8. **`verbose`**: When `true`, disables log batching for real-time log visibility. ### Example `e2e/jest.config.js`: ```javascript /** @type {import('@jest/types').Config.InitialOptions} */ module.exports = { rootDir: '..', testMatch: ['/e2e/**/*.test.js'], testTimeout: 120000, maxWorkers: 1, globalSetup: 'detox/runners/jest/globalSetup', globalTeardown: 'detox/runners/jest/globalTeardown', reporters: ['detox/runners/jest/reporter'], testEnvironment: 'detox/runners/jest/testEnvironment', verbose: true, }; ``` ``` -------------------------------- ### Start React Native Packager Source: https://wix.github.io/Detox/docs/introduction/your-first-test Before running Detox tests in debug configurations, ensure the React Native packager is running in parallel by executing `npm start`. ```bash npm start > react-native start ``` -------------------------------- ### Snapshot Testing Example Source: https://wix.github.io/Detox/docs/guide/taking-screenshots This example demonstrates a basic snapshot testing approach using Detox. It compares a captured image with a pre-existing snapshot. Ensure you have a tool like Applitools for advanced image comparison. ```javascript const fs = require('fs'); describe('Members area', () => { const snapshottedImagePath = './e2e/assets/snapshotted-image.png'; it('should greet the member with an announcement', async () => { const imagePath = (take screenshot from the device); // Discussed below expectBitmapsToBeEqual(imagePath, snapshottedImagePath); }); }); function expectBitmapsToBeEqual(imagePath, expectedImagePath) { const bitmapBuffer = fs.readFileSync(imagePath); const expectedBitmapBuffer = fs.readFileSync(expectedImagePath); if (!bitmapBuffer.equals(expectedBitmapBuffer)) { throw new Error(`Expected image at ${imagePath} to be equal to image at ${expectedImagePath}, but it was different!`); } } ``` -------------------------------- ### Install xcpretty for Xcodebuild Formatting Source: https://wix.github.io/Detox/docs/contributing/code/setting-up-the-dev-environment Install xcpretty, a formatter for xcodebuild output, using RubyGems. This tool helps in parsing and presenting build logs more effectively. ```bash gem install xcpretty ``` -------------------------------- ### Configure iOS Simulator Driver Source: https://wix.github.io/Detox/docs/articles/third-party-drivers Example configuration for the built-in iOS simulator driver. ```json { "ios.sim": { "type": "ios.simulator", "device": "...", "app": { "type": "ios.app", "binaryPath": "bin/YourApp.app" } } } ``` -------------------------------- ### Delete and Reinstall Application Before Launching Source: https://wix.github.io/Detox/docs/api/device Uninstalls and then reinstalls the app before launching, guaranteeing a completely fresh install. ```APIDOC ## POST /api/launchApp ### Description Uninstalls and reinstalls the app before launching. ### Method POST ### Endpoint `/api/launchApp` ### Parameters #### Request Body - **delete** (boolean) - Required - If true, deletes and reinstalls the app before launching. ``` -------------------------------- ### Install Detox Worker Source: https://wix.github.io/Detox/docs/api/internals Installs a Detox worker, which loads the expectation library and boots a device. This is typically handled by `init()`, but can be called separately if `init()` was invoked with `workerId: null`. ```javascript await installWorker({ global: {}, workerId: 'worker-1', }); ``` -------------------------------- ### Report test suite start Source: https://wix.github.io/Detox/docs/api/internals Reports the start of a test suite execution. Requires an installed worker. ```javascript await onRunDescribeStart({ name: 'Suite name' }); ``` -------------------------------- ### Install Emulator System Image Source: https://wix.github.io/Detox/docs/guide/android-dev-env Downloads the specified Android system image and accepts required licenses. ```bash $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager "system-images;android-28;default;x86_64" $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --licenses ``` -------------------------------- ### detox run-server Source: https://wix.github.io/Detox/docs/cli/run-server Starts a standalone Detox server for native codebase development. ```APIDOC ## detox run-server ### Description Starts a standalone Detox server. This tool is useful mostly for contributing to the native codebase of Detox, not for outside use. ### Parameters #### Options - **-p, --port** (number) - Optional - Port number (default: 8099) - **-l, --loglevel** (string) - Optional - Log level: fatal, error, warn, info, verbose, trace - **--no-color** (boolean) - Optional - Disable colorful logs - **--help** (boolean) - Optional - Show help ``` -------------------------------- ### Detailed Artifacts Configuration Example Source: https://wix.github.io/Detox/docs/config/artifacts Illustrates various artifact plugins and their settings, including root directory, path builder, and specific plugin configurations like instruments, log, uiHierarchy, screenshot, and video. ```json { "artifacts": { "rootDir": ".artifacts", "pathBuilder": "./config/pathbuilder.js", "plugins": { "instruments": {"enabled": false}, "log": {"enabled": true}, "uiHierarchy": "enabled", "screenshot": { "shouldTakeAutomaticSnapshots": true, "keepOnlyFailedTestsArtifacts": true, "takeWhen": { "testStart": false, "testDone": true } }, "video": { "android": { "bitRate": 4000000 }, "simulator": { "codec": "hevc" } } } }, "configurations": { "ios.sim.release": { // ... "artifacts": { "rootDir": ".artifacts/ios", "plugins": { "instruments": "all" } } } } } ``` -------------------------------- ### Boot Emulator via Command-Line Source: https://wix.github.io/Detox/docs/guide/android-dev-env Commands to launch an emulator instance using the Android SDK emulator binary. ```bash $ANDROID_HOME/emulator/emulator -verbose @Pixel_API_28_AOSP & ``` ```bash $ANDROID_HOME/emulator/emulator -verbose -no-window -no-audio -gpu swiftshader_indirect @Pixel_API_28_AOSP & ``` -------------------------------- ### Configure Detox Jest Test Runner Source: https://wix.github.io/Detox/docs/guide/migration Configure Jest setup timeout and reporting options in the .detoxrc.js file. This example reduces the setup timeout and disables spec and worker assignment reporters. ```javascript /** @type {Detox.DetoxConfig} */ module.exports = { testRunner: { $0: 'jest', args: { config: 'e2e/jest.config.js', _: ['e2e'] }, jest: { setupTimeout: 120000, reportSpecs: false, reportWorkerAssign: false, }, }, // … }; ``` -------------------------------- ### Initialize package.json Source: https://wix.github.io/Detox/docs/introduction/project-setup Create a default package.json file in the project root. ```bash npm init -y ``` -------------------------------- ### List iOS Device Types Source: https://wix.github.io/Detox/docs/introduction/project-setup Command to list available iOS simulator device types installed locally. ```bash xcrun simctl list devicetypes ``` -------------------------------- ### Enable spec reporting logs Source: https://wix.github.io/Detox/docs/config/testRunner Example of the log output generated when reportSpecs is enabled, showing test start and completion status. ```text 18:03:36.258 detox[40125] i Sanity: should have welcome screen 18:03:37.495 detox[40125] i Sanity: should have welcome screen [OK] 18:03:37.496 detox[40125] i Sanity: should show hello screen after tap 18:03:38.928 detox[40125] i Sanity: should show hello screen after tap [OK] 18:03:38.929 detox[40125] i Sanity: should show world screen after tap 18:03:40.351 detox[40125] i Sanity: should show world screen after tap [OK] ``` -------------------------------- ### installWorker Source: https://wix.github.io/Detox/docs/api/internals Loads the expectation library and boots a device. ```APIDOC ## installWorker([options]) ### Description Loads the expectation library and boots a device. Not required unless worker installation was disabled during init. ### Parameters #### Request Body - **options** (object) - Optional - Configuration object. - **global** (object) - Optional - Custom global scope reference. - **workerId** (string | null) - Optional - Unique ID for the worker. ### Response - **Promise** - Returns a promise that resolves when the worker is installed. ``` -------------------------------- ### Example Synchronization Debug Logs Source: https://wix.github.io/Detox/docs/config/session Sample output generated by Detox when an action exceeds the debugSynchronization threshold. ```text 09:41:00.941 detox[1337] i The app is busy with the following tasks: • There are 10 work items pending on the dispatch queue: "Main Queue ()". • UI elements are busy: - Layers pending animations: 96. - Layers needs layout: 173. - View needs layout: 74. - View needs display: 98. - Layers needs display: 90. • Run loop "Main Run Loop" is awake. ``` -------------------------------- ### Travis CI Configuration for Detox Source: https://wix.github.io/Detox/docs/introduction/preparing-for-ci A sample .travis.yml file to set up Detox tests on Travis CI. It includes environment setup, dependency installation, and Detox build/test commands. ```yaml language: objective-c osx_image: xcode8.3 branches: only: - master env: global: - NODE_VERSION=stable install: - brew tap wix/brew - brew install applesimutils - curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash - export NVM_DIR="$HOME/.nvm" && [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" - nvm install $NODE_VERSION - nvm use $NODE_VERSION - nvm alias default $NODE_VERSION - npm install react-native-cli --global - npm install detox-cli --global script: - detox build --configuration ios.sim.release - detox test --configuration ios.sim.release --cleanup ``` -------------------------------- ### Run Detox with Inspection Source: https://wix.github.io/Detox/docs/introduction/debugging Use the --inspect-brk flag to start Detox in a mode that allows attaching a debugger. ```bash detox test --inspect-brk -c android.emu.debug e2e/starter.test.js ``` -------------------------------- ### Basic Detox Configuration Structure Source: https://wix.github.io/Detox/docs/config/overview Defines the fundamental structure of a Detox configuration file, including devices, apps, and configurations. Use this as a starting point for your project's setup. ```javascript /* @type {Detox.DetoxConfig} */ module.exports = { devices: { device1: { /* ... */ }, device2: { /* ... */ }, }, apps: { app1: { /* ... */ }, app2: { /* ... */ }, }, configurations: { 'device1+app1': { device: 'device1', app: 'app1', }, /* ... */ }, }; ``` -------------------------------- ### Bitrise Workflow for Detox Tests Source: https://wix.github.io/Detox/docs/introduction/preparing-for-ci An example Bitrise .yml configuration for a workflow named 'tests'. This includes steps for cloning the repository, installing dependencies, and running Detox build and test commands. ```yaml --- format_version: 1.1.0 default_step_lib_source: https://github.com/bitrise-io/bitrise-steplib.git trigger_map: - push_branch: "*" workflow: tests workflows: _tests_setup: steps: - activate-ssh-key: {} - git-clone: inputs: - clone_depth: '' title: Git Clone Repo - script: inputs: - content: |- #!/bin/bash npm cache verify npm install title: Install NPM Packages before_run: [] after_run: [] _detox_tests: before_run: [] after_run: [] steps: - npm: inputs: - command: install -g detox-cli title: Install Detox CLI - npm: inputs: - command: install -g react-native-cli title: Install React Native CLI - script: inputs: - content: |- #!/bin/bash brew tap wix/brew brew install applesimutils title: Install Detox Utils - script: inputs: - content: |- #!/bin/bash detox build --configuration ios.sim.release title: Detox - Build Release App - script: inputs: - content: |- #!/bin/bash detox test --configuration ios.sim.release --cleanup title: Detox - Run E2E Tests tests: before_run: - _tests_setup - _detox_tests after_run: [] ``` -------------------------------- ### Configure Multiple Apps in One Configuration Source: https://wix.github.io/Detox/docs/config/apps Demonstrates how to define multiple apps and reference them within a single configuration block. ```json { "apps": { "driver.ios.release": { "type": "ios.app", "name": "driver", "binaryPath": "path/to/driver.app" }, "passenger.ios.release": { "type": "ios.app", "name": "passenger", "binaryPath": "path/to/passenger.app" } }, "configurations": { "ios.release": { "device": "simulator", "apps": ["driver", "passenger"], "build": "scripts/build-both-apps.sh", "start": "scripts/start-both-apps.sh" } } } ``` -------------------------------- ### CLI Error Example Source: https://wix.github.io/Detox/docs/guide/migration Example of an error message indicating incorrect CLI parameter usage. ```text ● Unrecognized CLI Parameter: Unrecognized option "workers". CLI Options Documentation: https://jestjs.io/docs/cli ``` -------------------------------- ### Detox Worker Assignment Log Example Source: https://wix.github.io/Detox/docs/config/testRunner Example of the log output generated when testRunner.jest.reportWorkerAssign is enabled. ```text 18:03:29.869 detox[40125] i starter.test.js is assigned to 4EC84833-C7EA-4CA3-A6E9-5C30A29EA596 (iPhone 12 Pro Max) ``` -------------------------------- ### Initialize Detox and Launch App with BeforeAll Hook Source: https://wix.github.io/Detox/docs/guide/cucumber-js-integration Use the BeforeAll hook to initialize Detox and launch the application. Ensure the timeout is sufficient for app launch. ```javascript BeforeAll({ timeout: 120 * 1000 }, async () => { await detox.init() await device.launchApp() }) ``` -------------------------------- ### Initialize Detox Source: https://wix.github.io/Detox/docs/introduction/project-setup Run the Detox initialization command to generate configuration files. ```bash detox init ``` -------------------------------- ### Report test start Source: https://wix.github.io/Detox/docs/api/internals Reports the start of a specific test. Use the invocations property to track re-runs. ```javascript await onTestStart({ title: 'should do something expected', fullName: 'Suite name should do something expected', invocations: 1, status: 'running', }); ``` -------------------------------- ### Create Android Virtual Device Source: https://wix.github.io/Detox/docs/guide/android-dev-env Initializes a new AVD with the specified name, device profile, and system image package. ```bash $ANDROID_HOME/cmdline-tools/latest/bin/avdmanager create avd -n Pixel_API_28_AOSP -d pixel --package "system-images;android-28;default;x86_64" ``` -------------------------------- ### Start Metro Bundler with Mock Mode Environment Variable Source: https://wix.github.io/Detox/docs/guide/mocking Execute the Metro bundler with the `MY_APP_MODE` environment variable set to `mocked` to enable the mock configuration. ```bash MY_APP_MODE=mocked npx react-native start ``` -------------------------------- ### Enable Automatic Server Start Source: https://wix.github.io/Detox/docs/config/session Explicitly enables the automatic starting of the Detox web socket server. ```json "session": { + "autoStart": true, "server": "ws://localhost:8099", "sessionId": "YourProjectSessionId" ``` -------------------------------- ### Launch App as New Instance in beforeEach Source: https://wix.github.io/Detox/docs/introduction/your-first-test To start every test from a fresh state, launch the app as a new instance in the `beforeEach` hook using `newInstance: true`. ```javascript beforeEach(async () => { await device.launchApp({ newInstance: true }); }); ``` -------------------------------- ### Start Metro Bundler with Mock Extension Source: https://wix.github.io/Detox/docs/guide/mocking Run the Metro bundler with the `--sourceExts` flag to prioritize your mock file extension. This is suitable for debug mode. ```bash npx react-native start --sourceExts mock.js,js,json,ts,tsx ``` -------------------------------- ### Install Jest TypeScript dependencies with pnpm Source: https://wix.github.io/Detox/docs/guide/typescript Install the necessary packages for Jest to work with TypeScript using pnpm. ```bash pnpm add --save-dev ts-jest @types/jest @types/node ``` -------------------------------- ### Install Jest TypeScript dependencies with Yarn Source: https://wix.github.io/Detox/docs/guide/typescript Install the necessary packages for Jest to work with TypeScript using Yarn. ```bash yarn add --dev ts-jest @types/jest @types/node ``` -------------------------------- ### Initialize Detox Project Source: https://wix.github.io/Detox/docs/cli/init Run this command in your project's root directory to create template files for Detox configuration and a starter test suite. It generates .detoxrc.js, e2e/jest.config.js, and e2e/starter.test.js. ```bash detox init ``` -------------------------------- ### Install Jest TypeScript dependencies with npm Source: https://wix.github.io/Detox/docs/guide/typescript Install the necessary packages for Jest to work with TypeScript using npm. ```bash npm install --save-dev ts-jest @types/jest @types/node ``` -------------------------------- ### Test App Launch with User Activity Source: https://wix.github.io/Detox/docs/guide/mocking-user-activity An example test case demonstrating how to launch an app with a user activity and verify that an element related to that activity is visible. Ensure the `activity` object is defined elsewhere. ```javascript describe('Background user activity', () => { it('Launch with user activity', async () => { await device.launchApp({userActivity: activity}) await expect(element(by.text('From user activity'))).toBeVisible(); }); }); ``` -------------------------------- ### Install Monorepo Dependencies with Yarn Source: https://wix.github.io/Detox/docs/contributing/code/setting-up-the-dev-environment Install all project dependencies for the monorepo using Yarn. This command should be run after cloning the repository. ```bash yarn install ``` -------------------------------- ### Detox Runtime Error Example Source: https://wix.github.io/Detox/docs/guide/migration Example of the error message generated when an await statement is missing for an asynchronous Detox API call. ```text FAILED DetoxRuntimeError: The pending request #246 ("invoke") has been rejected due to the following error: Detox has detected multiple interactions taking place simultaneously. Have you forgotten to apply an await over one of the Detox actions in your test code? ``` -------------------------------- ### Build with Specific Configuration Source: https://wix.github.io/Detox/docs/cli/build Specifies a particular device configuration for the build process. ```bash detox build --configuration yourConfiguration ``` -------------------------------- ### iOS Visibility Error Example Source: https://wix.github.io/Detox/docs/troubleshooting/running-tests Example of an error message encountered when a view fails to meet the required visibility threshold on iOS. ```text Test Failed: View "" is not visible: view does not pass visibility threshold (0% visible of 75% required) ``` -------------------------------- ### Track Test Start with Before Hook Source: https://wix.github.io/Detox/docs/guide/cucumber-js-integration Call detox.onTestStart() within the Before hook to inform Detox about the start of a new test. This is crucial for recording logs and artifacts. ```javascript Before(async (message: ITestCaseHookParameter) => { const { pickle } = message await detox.onTestStart({ title: pickle.uri, fullName: pickle.name, status: 'running', }) }) ``` -------------------------------- ### Force Detox Start Ignoring Errors Source: https://wix.github.io/Detox/docs/cli/start Use the --force option to ignore any errors encountered during the execution of the 'start' scripts and continue the process. ```bash detox start -c yourConfiguration --force ``` -------------------------------- ### Start React Native Packager Source: https://wix.github.io/Detox/docs/guide/developing-while-writing-tests Manually start the React Native packager if it's not already running. This allows for JavaScript code modifications to be reloaded into the app. ```bash npx react-native start ``` -------------------------------- ### Build with Default Configuration Source: https://wix.github.io/Detox/docs/cli/build Executes the build command using the default configuration when only one is defined. ```bash detox build ``` -------------------------------- ### Install Watchman using Homebrew Source: https://wix.github.io/Detox/docs/contributing/code/setting-up-the-dev-environment Install Watchman, a tool for watching filesystem changes, using the Homebrew package manager. This is a common dependency for React Native development. ```bash brew install watchman ``` -------------------------------- ### Set Internal Registry and Install Dependencies (Wix Internal) Source: https://wix.github.io/Detox/docs/contributing/code/setting-up-the-dev-environment For Wix internal contributors, set the internal npm registry environment variable before installing dependencies with Yarn. ```bash export YARN_NPM_REGISTRY_SERVER="" yarn install ``` -------------------------------- ### Launching a New Instance of the App Source: https://wix.github.io/Detox/docs/api/device Launch the app with `newInstance: true` to terminate and restart it. The default behavior is `false`, attempting to resume the app. ```javascript await device.launchApp({newInstance: true}); ``` -------------------------------- ### Detox Test with Options Source: https://wix.github.io/Detox/docs/cli/test Example of using the detox test command with specific options like configuration and showing configuration details. ```bash detox test -c ios.debug --showConfig ``` -------------------------------- ### Install React Native CLI Globally Source: https://wix.github.io/Detox/docs/contributing/code/setting-up-the-dev-environment Install the React Native command line interface globally using npm. This tool is used for managing React Native projects. ```bash npm install react-native-cli --global ```