DEV Community

Cover image for Eliminating CI Bottlenecks in Detox E2E Suites
Amit chakraborty
Amit chakraborty

Posted on Originally published at amitchakraborty.dev

Eliminating CI Bottlenecks in Detox E2E Suites

Imagine a lead engineer standing over a workstation at 7:00 PM on a Thursday. They are trying to ship a critical security patch for a React Native application. Every time they push a commit, the GitHub Actions pipeline kicks off a suite of 150 Detox end-to-end tests. Forty minutes later, the pipeline fails—not because of a bug, but because a single login test timed out while waiting for the bundler.

The engineer triggers a "Re-run failed jobs." Another 40 minutes pass. This time, the suite passes, but the delay has pushed the release into the next day. This cycle costs the team roughly 15 hours of engineering time per week in "babysitting" CI. The immediate impulse is to throw money at the problem: double the number of CI workers or increase the timeout limits. Without instrumentation, however, these "fixes" often result in higher monthly bills without a proportional decrease in cycle time.

The problem is that Detox is a black box by default. You see the start time and the end time, but you cannot see the "dead air" where the simulator is idling, the bridge is loading, or the test runner is waiting for an asynchronous event that will never fire. To fix a slow suite, you must first instrument it to distinguish between infrastructure overhead and actual test logic.

Why CI instrumentation fails by default

Most teams rely on the default Jest output provided by Detox. This tells you that login.spec.js took 120 seconds. It does not tell you that:

  1. 60 seconds were spent waiting for the iOS Simulator to boot.
  2. 20 seconds were spent building the application (which should have been a cached artifact).
  3. 15 seconds were spent on beforeEach hooks resetting the device state.
  4. Only 25 seconds were spent executing actual test interactions.

When you lack this breakdown, you optimize the wrong things. You might spend a week refactoring test code to be more efficient when the real bottleneck is the applesimutils boot sequence or a bloated .app bundle being copied to the simulator on every worker.

In Detox v20 and above, the internal architecture moved to a more robust client-server model, but this added layers of communication that can mask latency. If the Detox server is under-resourced on a CI runner, the "action-acknowledge" cycle slows down, making tests appear slow when the app is actually performing fine.

Step 1: Enabling and capturing trace logs

The first step is to move beyond the standard loglevel: info. You need the timeline of every internal Detox event to identify where the "dead air" exists.

Modify your CI execution command to include the --trace-log flag and redirect it to a file that can be uploaded as an artifact.

detox test --configuration ios.sim.release --trace-log detox.log --record-logs all
Enter fullscreen mode Exit fullscreen mode

Why this matters: The detox.log file contains JSON-formatted entries for every interaction between the test runner, the Detox server, and the app.
How to confirm: After the run, check your CI artifacts. You should see a detox.log file. Open it; if you see entries like deliverPayload and appReady, the instrumentation is active.

Step 2: Extracting Lifecycle Timings

A raw log file is difficult to read. You need to calculate the duration of specific lifecycle phases. Specifically, you want to measure the Time to First Interaction (TTFI). This is the delta between the CI job starting and the first expect() or tap() being executed.

Create a script (e.g., scripts/analyze-detox-logs.js) to parse the log for these specific markers:

  • session_start: When the Detox server is ready.
  • boot_device_start / boot_device_done: How long the simulator takes to reach a usable state.
  • install_app_start / install_app_done: The cost of moving the binary to the device.
  • app_ready: When the detox.init() call finally resolves.
// Example logic for parsing the trace log
const fs = require('fs');
const logContent = fs.readFileSync('detox.log', 'utf8');
const lines = logContent.split('\n').filter(Boolean).map(JSON.parse);

const bootStart = lines.find(l => l.msg === 'booting device')?.ts;
const bootEnd = lines.find(l => l.msg === 'device booted')?.ts;
const bootDuration = bootEnd - bootStart;

console.log(`Simulator Boot Time: ${bootDuration / 1000}s`);
Enter fullscreen mode Exit fullscreen mode

The Goal: If boot time exceeds 30 seconds on a Mac mini or 60 seconds on a virtualised GitHub runner, your bottleneck is infrastructure. No amount of test refactoring will fix this.

Step 3: Implementing a Custom Jest Reporter for CI

Standard JUnit reports used by CI providers (like CircleCI or Azure DevOps) often only show the total duration of a test file. To find the "long poles" in your suite, you need a reporter that captures the duration of individual it blocks and their setup/teardown costs.

Install jest-junit or a similar reporter, but configure it to include "properties" for each test case.

// jest.config.js
module.exports = {
  reporters: [
    'default',
    ['jest-junit', {
      outputDirectory: './artifacts',
      outputName: 'junit.xml',
      addFileAttribute: 'true',
      ancestorSeparator: ' › ',
      classNameTemplate: '{classname}',
      titleTemplate: '{title}',
    }]
  ]
};
Enter fullscreen mode Exit fullscreen mode

How to confirm: View the junit.xml file. Look for the time attribute on each <testcase> element. If a single test takes more than 30 seconds, it is a candidate for splitting. In my experience, tests longer than 45 seconds have a 3x higher probability of failing due to random network jitter or UI synchronization issues.

Step 4: Visualising the Timeline

Detox trace logs are compatible with Chrome's tracing tool (chrome://tracing). This is the most effective way to see overlapping events.

  1. Take the detox.log (if it was generated with the --trace-log flag).
  2. Open Chrome or Edge and navigate to chrome://tracing.
  3. Drag and drop the log file into the window.

You will see a Gantt-style chart. Look for large gaps where the "Test Runner" thread is empty while the "App" thread is busy. This usually indicates that Detox is waiting for the "App Readiness" signal.

In React Native 0.71+, this is often caused by infinite animations or third-party libraries (like certain analytics SDKs) that keep the bridge busy. Detox will not interact with the app as long as there is pending work on the main thread or the bridge, unless you explicitly configure device.setURLBlacklist().

What it costs, and when not to do it

Instrumentation is not free. Enabling --trace-log and --record-logs all can produce log files and videos exceeding 1GB for a large suite.

  1. Storage Costs: If you run 50 builds a day, storing 1GB of artifacts per build can quickly exhaust your CI storage quotas. I recommend only enabling full trace logging on main branch builds or when a PR is specifically tagged with label: debug-ci.
  2. Execution Overhead: Writing verbose logs to disk on a containerised CI runner with slow I/O can increase test duration by 3-5%. This is a trade-off: you accept a slight slowdown in exchange for the data needed to achieve a 50% reduction later.
  3. Noise: Do not instrument every single run for a small team with a 5-minute suite. If your total CI time is under 10 minutes, the engineering cost of maintaining the instrumentation scripts outweighs the potential savings.

At your level

Starting out

If you are a student or a junior engineer, focus on the loglevel: trace output in your local terminal. Before you push code, observe how many "retries" Detox performs while waiting for an element. If you see dozens of wait for expectation logs before a success, your test is fragile. Use waitFor() with a visible constraint rather than relying on Detox's internal polling to find an element that hasn't appeared yet.

Working engineer

Your priority is the "Test Density" metric. This is the ratio of time spent on expect and tap actions versus time spent in beforeEach or afterEach. If your density is low, you are likely resetting the entire app state (logging out and in) for every single test. Move to a "Logged In" state by injecting a session cookie or mocking the async storage, rather than repeating the UI login flow 100 times.

Senior or staff

You own the architecture of the CI pipeline. Use the metrics gathered from your custom reporters to implement Dynamic Parallelisation. Instead of spliting tests alphabetically across 4 workers, use the timing data from the previous main build to distribute tests so that every worker finishes within 10 seconds of the others. This eliminates the "straggler" effect where one worker runs for 30 minutes while the others finish in 10.

Lead or director

Focus on the "Cost per Green Build." Calculate the total CI spend divided by the number of successful merges. Use the instrumentation data to justify the investment in higher-tier CI runners (e.g., moving from GitHub-hosted to self-hosted M2 Mac minis). If the data shows that 40% of your CI time is spent on "Simulator Boot," you can prove that buying faster hardware will pay for itself in three months by reducing developer idle time.

In the interview

The Question: "Our E2E tests are slow and flaky in CI. How do you approach fixing them?"

The Weak Answer: "I would increase the timeouts, add more retries, and maybe try to run the tests in parallel using more workers." This is weak because it treats the symptom, not the cause, and increases CI costs without addressing the underlying inefficiency.

The Strong Answer: "I would start by instrumenting the suite to separate infrastructure overhead from test execution. I'd enable Detox trace logs to measure the 'Time to First Interaction' and identify if the bottleneck is the simulator boot sequence, the app installation, or the sync engine. I'd look for 'dead air' in the Chrome tracing view to see if the Detox bridge is waiting on infinite animations. Once I have the timing data for each test, I'd implement parallelisation based on historical duration to ensure an even load across workers."

The Senior/Staff Follow-up: An interviewer might ask, "How do you handle the trade-off between test isolation and suite speed?"
A candidate who has actually done this will discuss the "Reset vs. Reuse" dilemma. They will explain that while resetting the simulator between every test is the most stable approach, it adds a 30-60 second penalty per test. They might suggest a "Hybrid Isolation" strategy: resetting the app state (clearing cache/storage) between tests but only rebooting the simulator if a test fails or after a set number of runs. They should mention the specific Detox configuration reinstallApp: false and how it impacts the feedback loop.


Amit Chakraborty is a founding engineer and senior architect — React Native, AI/RAG systems and production architecture. Portfolio: www.amitchakraborty.dev · LinkedIn · GitHub. Open to senior and founding engineering roles, remote worldwide.

Top comments (0)