<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Giulia Brocchi on Medium]]></title>
        <description><![CDATA[Stories by Giulia Brocchi on Medium]]></description>
        <link>https://medium.com/@giulia.brocchi?source=rss-68ff125aaa1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*4_gPOrc8DN0CkwOL</url>
            <title>Stories by Giulia Brocchi on Medium</title>
            <link>https://medium.com/@giulia.brocchi?source=rss-68ff125aaa1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 10:32:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giulia.brocchi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Automating mobile tests with AI]]></title>
            <link>https://medium.com/profusion-engineering/automating-mobile-tests-with-ai-5162a37f2526?source=rss-68ff125aaa1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5162a37f2526</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-testing]]></category>
            <category><![CDATA[appium]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[mcps]]></category>
            <dc:creator><![CDATA[Giulia Brocchi]]></dc:creator>
            <pubDate>Thu, 02 Jul 2026 13:06:33 GMT</pubDate>
            <atom:updated>2026-07-02T13:06:33.921Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to build a system where mobile tests live as markdown files and use an MCP to bridge the simulator to the agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*pSFJ2m-9nvqdOP7w-Ef6tw.png" /></figure><h3><strong>1. Introduction</strong></h3><p>Agents are great at generating code, but the feedback loop is broken. An agent writes a login screen, but how does it verify if the button actually works? With web, it is simple: the agent can just inspect the DOM since in the end everything turns into HTML code. With mobile, things get more complicated. The accessibility tree exists, but it’s buried behind platform-specific toolchains and there is no universal selector language.</p><p>Telling an AI “test this” without any structure is a way to waste tokens. It guesses selectors and re-discovers layouts it already mapped, burning context on repetitive reasoning while the same questions cycle through every invocation. We need a deterministic, repeatable way for agents to test mobile output, something that scales past a single ad-hoc prompt.</p><h3><strong>2. Understanding the problem</strong></h3><h4><strong>2.1 No universal element tree</strong></h4><p>Web has the DOM, which has one tree, one selector syntax, and works everywhere. An agent can open a browser, query <em>document.querySelector</em>, and find any element on any page. The tooling is built-in and the answer to “is this button visible?” is a single line of JavaScript.</p><p>Mobile has none of that. Each platform exposes a different accessibility tree and its own selector language, so an element addressable on iOS is unreachable on Android under a different name, or completely invisible when the framework refuses to bridge its internal state to the accessibility layer. There is no universal way to say “find the login button.”</p><p>The consequence is that every tool wanting to interact with a mobile app has to learn these trees separately. An agent that learned to tap a button on iOS has learned nothing about tapping the same button on Android. Mobile is not harder in degree. The foundation that makes web testing approachable simply does not exist here.</p><h4><strong>2.2 Simulator access is non-trivial</strong></h4><p>This should be easy. On the web, you open a browser window and you’re done. Mobile automation requires assembling a chain of tools that web developers never think about: simulators requiring separate bridging apps alongside signed provisioning profiles, all coordinated by a protocol translation server. A “hello world” mobile test consumes an afternoon of environment setup before you write a single assertion. The equivalent on the web takes two minutes. This is why mobile E2E testing gets abandoned: the toolchain friction is higher than the perceived value of the test.</p><h4><strong>2.3 E2E test code requires maintenance</strong></h4><p>Traditional XCTest (iOS) and Espresso (Android) tests live in the codebase, so every UI refactor breaks them. This means that an engineer will need to not only develop the code but also change the tests to meet the new requirements. And, to be honest, most projects have E2E tests just to generate metrics that don’t reflect reality. People tend to write test cases only for the happy path and the real bugs only surface once they reach the end-user.</p><h4><strong>2.4 Token cost for unstructured testing</strong></h4><p>An agent without a plan will re-discover elements it already encountered three steps ago and burn thousands of tokens on repetitive screen identification. A full end-to-end flow through unstructured prompting can easily consume an insane amount of tokens. Multiply by a regression suite and you’re looking at millions of tokens for what should be a mechanical verification.</p><h3><strong>3. The solution</strong></h3><p>What we aim for is a simple way to tell the agents to test our app, without any code, but with an underlying structured base. The simplest way of doing that is using an MCP to coordinate the simulator access and interactions and define the test cases using natural language on <em>.md</em> files.</p><p>There are multiple MCPs available for this, but the one that gave me the best results was the <a href="https://github.com/appium/appium-mcp">MCP Appium</a>, so we will use it for the examples.</p><p>Inside our project, the tests architecture will look something like this:</p><pre>AGENTS.MD                       // General instructions for the AI<br>/skills<br>    test-automation/SKILL.md    // The skill to instruct the agent into executing the tests<br>    flow-generation/SKILL.md    // The skill to instruct the agent into creating new flows<br>/e2e_tests<br>    /flows<br>        *.md                    // One file per flow on the app (e.g. login, list_posts, add_posts)<br>    /suites<br>        *.md                    // A group of flows (e.g. regression, smoke)</pre><p>Let’s dive deep into each file to build a good structure for your agents to automate tests.</p><h4><strong>3.1 The AGENTS.MD file</strong></h4><p>The <em>AGENTS.MD</em> file sits at the project root and acts as the contract between your app and the AI. Every agent that touches the codebase reads it first. This post will not cover all the aspects needed to write a good <em>AGENTS.MD</em>, there are multiple examples on the internet already. What is important here is to add instructions for the agent on how and when to run or update the tests and general descriptions of the project.</p><pre>// ... other project patterns and general instructions. Example:<br><br>## Localizations<br><br>Labels and texts are localized via `AppStrings`. The available languages are `en` and `pt` and they update according to the device&#39;s language.<br><br>// Instructions on running the tests<br><br>## Testing the app<br><br>- **Automation**: Via `@appium-mcp` MCP server. See skill `/skills/test-automation/SKILL.md` for conventions.<br>- **Test suites**: `/e2e_tests/suites/` — sequence of flows for smoke/regression runs<br>- **Flow specs**: `/e2e_tests/flows/` — per-feature declarative test specs (happy path, edge cases, error states)<br><br>When updating a feature, also update the corresponding flow `.md`. Add edge, loading,<br>and error cases. If a test step fails because the actual label differs from the spec,<br>update the flow file with the correct label before retrying — the spec is the source of<br>truth, not a frozen artifact.</pre><h4><strong>3.2 Test Automation skill</strong></h4><p>This skill is what an AI agent loads when you say “run the smoke tests.” It translates the natural language of a flow spec into concrete MCP tool calls, enforces what a pass and a fail actually mean, and defines the structure of the report.</p><p>The most important thing the skill does is mapping every flow action to a specific tool (in our case, an Appium function). When a spec says <em>find (label: “Sign in”)</em>, the agent doesn’t pause to think about which function to call, it just looks up <em>appium_find_element</em> and runs it. This is the difference between a test that takes five seconds and a test that burns 10K tokens, re-deciding how to look for a button it already found three steps ago.</p><p>Alongside the tool mapping, the skill defines an assertion vocabulary so every result has the same format. Every step in a flow spec carries an annotation, and the skill translates that annotation into a concrete reaction: aborting the flow when a required element is missing, logging a warning when an unexpected one appears, or capturing a screenshot and continuing. By encoding these outcomes in the skill rather than leaving them to the agent’s judgment, you get the same behavior on every run regardless of which model is executing.</p><p>The skill also tells the agent what a good result looks like. After each flow, the agent prints a results table that traces every step from what was expected through what actually happened to a verdict backed by screenshot evidence. A one-sentence summary follows each failure: expected X, got Y. The format is designed for both a human scanning in seconds and an orchestrator agent feeding it into the next pipeline stage with full context.</p><p>It’s also important to highlight on the skill some project-specific patterns that help the agent to reduce the amount of reasoning and go for a straightforward solution. A screen detection strategy tells the agent which element confirms it landed on the right screen after navigation, so it never taps blindly on a stale view. A locale handling procedure catches the case where a label was translated into the device language, preventing a false failure when “Sign in” became “Entrar.”</p><p>Here’s what the skill looks like in practice:</p><pre>---<br>name: test-automation<br>description: Run mobile test automation flows against the app using Appium MCP. Use when the user asks to run tests, test a flow, verify a feature, run automation. Do not use for exploratory testing or single ad-hoc taps — use for structured flow-based testing.<br>---<br><br>Agent that runs declarative mobile test flows using `@appium-mcp`.<br><br>## How this works<br><br>You read a **flow spec** from `test/flows/&lt;name&gt;.md`, follow its steps using<br>`@appium-mcp` tools, assert results against `[expect: pass|fail]` annotations,<br>and produce a results table. The flow file IS the test — no code to write.<br><br>## Tool mapping — flow actions → Appium MCP calls<br><br>Each action in a flow spec maps to a specific `@appium-mcp` tool call.<br>Do not improvise — use the exact tool listed.<br><br>| Flow action                         | Appium MCP tool(s)                                                      |<br>| ----------------------------------- | ----------------------------------------------------------------------- |<br>| `launch`                            | `appium_app_lifecycle(action: &quot;activate&quot;)`                              |<br>| `terminate`                         | `appium_app_lifecycle(action: &quot;terminate&quot;)`                             |<br>| `find (label: &quot;...&quot;)`               | `appium_find_element(strategy: &quot;accessibility id&quot;, value: &quot;...&quot;)`       |<br>| `tap_label (label: &quot;...&quot;)`          | `appium_find_element(...)` → `appium_gesture(action: &quot;tap&quot;, elementId)` |<br>| `type (value: &quot;...&quot;)`               | `appium_set_value(elementId, text: &quot;...&quot;)`                              |<br>| `screenshot`                        | `appium_screenshot`                                                     |<br>| `scroll_to (label: &quot;...&quot;)`          | `appium_scroll_to_element(strategy: &quot;accessibility id&quot;, value: &quot;...&quot;)`  |<br>| `swipe (direction: &quot;...&quot;)`          | `appium_gesture(action: &quot;swipe&quot;, direction: &quot;...&quot;)`                     |<br>| `accept_alert`                      | `appium_alert(action: &quot;accept&quot;)`                                        |<br>| `dismiss_alert`                     | `appium_alert(action: &quot;dismiss&quot;)`                                       |<br>| `background_app`                    | `appium_app_lifecycle(action: &quot;background&quot;)`                            |<br>| `assert_visible (label: &quot;...&quot;)`     | `appium_find_element(...)` → check `.visible`                           |<br>| `assert_not_visible (label: &quot;...&quot;)` | `appium_find_element(...)` → pass if NOT found                          |<br>| `alert_contains (text: &quot;...&quot;)`      | `appium_alert(action: &quot;get_text&quot;)` → substring match                    |<br>| `wait_for (label: &quot;...&quot;)`           | `appium_find_element(...)` in loop, sleep 500ms, up to timeout          |<br><br>## Assertion annotations<br><br>| Annotation       | Meaning                                 | On failure                                                  |<br>| ---------------- | --------------------------------------- | ----------------------------------------------------------- |<br>| `[expect: pass]` | Element/text/state MUST exist or match. | Screenshot → log → **abort flow**.                          |<br>| `[expect: fail]` | Element/text/state MUST NOT exist.      | Screenshot → log → **continue flow** (unexpected presence). |<br><br>## Failure protocol<br><br>One failure → one screenshot → one log line → move on.<br>Do not retry, do not speculate, do not debug interactively.<br><br>1. `appium_screenshot` → save to `temp/tests/&lt;flow&gt;_step&lt;N&gt;_fail.png`<br>2. Log: `[FAIL] &lt;flow&gt; / &lt;scenario&gt; / step &lt;N&gt;: expected &quot;&lt;expected&gt;&quot;, got &quot;&lt;actual&gt;&quot;`<br>3. Abort the flow. If another flow depends on it, skip that one too.<br><br>## Results output<br><br>After every flow, print a results table:<br><br>| Scenario       | Step       | Expected             | Actual                       | Result | Evidence   |<br>| -------------- | ---------- | -------------------- | ---------------------------- | ------ | ---------- |<br>| happy flow     | Launch app | Login screen visible | &quot;Sign in&quot; found              | PASS   | screenshot |<br>| wrong password | Submit     | Error alert          | Alert: &quot;Invalid credentials&quot; | PASS   | screenshot |<br><br>## Summary<br><br>PASSED: X/Y assertions across Z scenarios<br>FAILED: ... (with details)<br><br>Follow the table with exactly one sentence per failure — expected vs actual, no root cause speculation.<br><br>## Screen detection<br><br>Do not guess which screen you&#39;re on. Call Appium&#39;s tool `generate_locators`, check for<br>a screen-identifying element. If absent, log the AX tree and fail the step.<br><br>&lt;!-- Example screen identifiers — yours will differ --&gt;<br>&lt;!-- | Screen    | Identifying element  | --&gt;<br>&lt;!-- | --------- | -------------------- | --&gt;<br>&lt;!-- | Login     | title: &quot;Sign in&quot;     | --&gt;<br>&lt;!-- | Home      | title: &quot;Home&quot;        | --&gt;<br><br>## Locale handling<br><br>&lt;!-- Change these specs to match your project&#39;s structure --&gt;<br>If the device language is not English, labels will differ from the flow spec.<br>At session start, detect the locale. Check Resources/_.lproj/_.strings for the exact localized values.<br>On a `find` failure in a non-English locale, snapshot the AX tree and search for the semantic equivalent of the expected label. Update the flow file if you find it, fail the step if you don&#39;t.</pre><h4><strong>3.3 The flow files</strong></h4><p>Every user journey in your app gets one of these files, and every one follows the same skeleton. The goal is to leave the agent no room to interpret what you meant. An agent that has to guess whether “check login” means verify a button exists or confirm a navigation happened is an agent that will guess wrong half the time. And the best part here is that you can write all of this file without any line of code, using just natural language.</p><p>The suggested template has four sections, and each one removes a specific ambiguity.</p><p><strong>Prerequisites:</strong> answer the question “what needs to be true before this flow starts?” The agent shouldn’t have to wonder whether the app is installed, which account to use, or what locale the device is in. A missing prerequisite is a common source of false failures, even on unit tests.</p><p><strong>Given:</strong> locks the starting state. It tells the agent what screen the app should be on and what condition the session is in before the first step. An agent that launches the app and finds itself on the home screen because the last test forgot to log out is an agent that will report a pass on a login flow that never ran.</p><p><strong>Happy flow:</strong> is the common path, what the journey was designed to do primarily. Each step is a single imperative action with an explicit annotation and usually there are no conditionals. The agent will execute the steps one by one, unless it fails.</p><p><strong>Edge cases:</strong> cover what goes wrong, for example wrong password, network timeout, empty form submission. Each scenario gets its own block with its own starting state, steps, and assertions. Separating edge cases from the happy path means the agent never has to branch mid-flow.</p><p>Here’s an example of a <em>/flows/login.md</em> file that follows this structure:</p><pre># Flow: Login<br><br>## Prerequisites<br><br>- App installed<br><br>## Given: app is terminated<br><br>## Happy flow: login with credentials<br><br>### Step 1: Launch app<br><br>- Action: launch [expect: pass]<br><br>### Step 2: Verify login screen<br><br>- Action: find (label: &quot;Sign in&quot;) [expect: pass]<br><br>### Step 3: Enter credentials<br><br>- Action: tap_label (label: &quot;User name (email address)&quot;)<br>- Action: type (value: &quot;admin&quot;)<br>- Action: tap_label (label: &quot;Password&quot;)<br>- Action: type (value: &quot;admin&quot;)<br><br>### Step 4: Submit and verify<br><br>- Action: tap_label (label: &quot;Sign in&quot;)<br>- Action: assert_not_visible (label: &quot;Sign in&quot;) [expect: pass]<br>- Action: find (label: &quot;Home&quot;) [expect: pass]<br>- Action: screenshot<br><br>## Edge case: wrong password<br><br>### Step 1: Enter wrong password<br><br>- Action: tap_label (label: &quot;Password&quot;)<br>- Action: type (value: &quot;wrongpassword&quot;)<br><br>### Step 2: Verify error<br><br>- Action: tap_label (label: &quot;Sign in&quot;)<br>- Action: alert_contains (text: &quot;invalid&quot;) [expect: pass]<br><br>### Step 3: Dismiss and stay on login<br><br>- Action: dismiss_alert<br>- Action: find (label: &quot;Sign in&quot;) [expect: pass]</pre><h4><strong>3.4 Flow generation skill</strong></h4><p>Here’s the part where this whole system bends back on itself in a useful way. The flow files we just described are the exact same files the AI reads when it executes tests. Which means the AI can also write them. You don’t need a human to step in and waste time writing hundreds of files because the app is complex and has too many journeys. You just need a second skill that teaches the agent how to look at your codebase and produce a flow spec from it.</p><p>In the flow generation skill, the agent walks through your feature the way a tester would, tracing the user journey from the screens they visit through the interactions they perform to the failure points they encounter and the accessibility labels that make each element reachable.</p><p>From those screens and labels, the agent assembles a flow file that follows the same template as every other flow: prerequisites to prevent false failures coupled with a locked starting state. From there, it maps out a linear happy flow supported by isolated edge case scenarios. When it’s done, it shows you the file and asks for approval. A good practice is to never auto-commit a spec without review, since the AI can still make mistakes. Also, if a flow already exists for that feature, it updates it in place and shows a diff.</p><p>Here’s how it can look like:</p><pre>---<br>name: flow-generation<br>description: Generate new test flow specs for the app. Use when the user asks to create a test flow, generate a flow spec, write a flow for a feature, or add test coverage for a screen. Do not use for running tests.<br>---<br><br>## How this works<br><br>You read a feature&#39;s source files, map its navigation and interactive elements,<br>extract real accessibility labels from the code, and produce a flow spec<br>following the template. The output is a `.md` file committed to `test/flows/` —<br>no test code, just a structured document the `test-automation` skill can execute.<br><br>## Discovery — mapping a feature to a flow<br><br>For the feature under test, read these files in order:<br><br>&lt;!-- Project-specific: adjust these patterns to your framework --&gt;<br><br>1. **Screen** — what views exist, what&#39;s tappable, what states (loading, error, empty)<br>2. **ViewModel** — what data flows in, what user actions trigger mutations, what errors<br>3. **Coordinator** — what screens does this navigate to/from, entry and exit points<br>4. **Worker** — what network calls happen, what can fail<br><br>From this, extract:<br><br>- Screens visited (ordered)<br>- Interactive elements per screen<br>- State transitions (loading → success, loading → error, idle → empty)<br>- Error paths (network failure, validation rejection, auth expiry)<br><br>## Flow spec template<br><br>Every generated flow follows this structure:<br><br>```markdown<br># Flow: &lt;descriptive name&gt;<br><br>## Prerequisites<br><br>- &lt;state requirements, account, locale&gt;<br><br>## Given: &lt;starting state&gt;<br><br>- &lt;screen and session condition&gt;<br><br>## Happy flow: &lt;primary user goal&gt;<br><br>### Step 1: &lt;action description&gt;<br><br>- Action: &lt;action&gt; [expect: pass]<br><br>### Step 2: &lt;action description&gt;<br><br>- Action: &lt;action&gt; [expect: pass]<br><br>## Edge case: &lt;failure scenario&gt;<br><br>...<br><br>## Edge case: &lt;another failure scenario&gt;<br><br>...<br>```<br><br>Rules:<br><br>- Happy flow: one path, no branches.<br>- Edge cases: cover validation failure.<br>- Add wait_for steps between launch and first assertion if loading states exist.<br>- After every navigation, assert the new screen is visible.<br>- Use exact labels from the code, not placeholders.<br><br>## Review and commit<br><br>Show the complete flow file to the user. Ask for confirmation before writing.<br>Never auto-commit without review. If a flow already exists for this feature, update it in-place and show a diff.</pre><h4><strong>3.5 Test suites</strong></h4><p>A single flow file tests one feature. A test suite stitches several flows together, specifies the order in which to run them, and who depends on whom.</p><p>The dependency column is the important one. The suite declares them explicitly: flow 2 depends on flow 1, so if 1 goes red, 2 through 6 get skipped. This keeps a single failure from producing a cascade of six red results that all trace back to the same root cause.</p><p>This structure becomes especially useful when the AI is doing work that touches multiple parts of the app at once. With a suite, you just say “run the smoke tests” and the agent works through the dependency table, skipping only what’s blocked by an upstream failure.</p><p>You can have as many suites as you need. Each one is just a markdown table with a different list of flows and dependencies, and the same mechanism drives all of them:</p><pre># Test Plan: Smoke<br><br>| #   | Flow               | Depends on | Notes               |<br>| --- | ------------------ | ---------- | ------------------- |<br>| 1   | Login — happy path | —          | Terminate app first |<br>| 2   | Terms — list       | 1          |                     |<br>| 3   | Terms — details    | 2          |                     |<br>| 4   | Posts — create     | 1          |                     |<br>| 5   | Profile — view     | 1          |                     |<br>| 6   | Profile — logout   | 5          | Must run last       |<br><br>**Abort-on-failure**: If flow 1 fails, skip all.</pre><h3><strong>4. How to use it</strong></h3><p>By this point you have all the files in place. Now all you need to do is interact with an agent so it can start testing.</p><p>You make a change to the app, like adding a new screen or refactoring the login flow. Now, open your AI agent of choice and tell it what to test. Don’t be too vague (e.g. “check if the app works”, “run some tests”), remember that you need to provide all the context so the AI knows exactly what to do. For example, provide the context of what you changed in the code and say “run the login flow and verify the error cases still pass.”</p><p>The agent loads the test automation skill, reads the suite or flow file you pointed at, and works through every step, managing the entire execution lifecycle while automatically capturing assertions. You can let it test while you do something else. When it finishes, you get the results table in the chat, or in a file if you instruct it to save the results. The tests execute in the same conversation where you wrote the code, not in a separate runner or dashboard.</p><p>If a step fails because a label changed, the agent updates the flow file with the correct label and retries. If a step fails because the app is actually broken, you know immediately. You can fix the code, say “run it again,” and move on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Vz3u6Ic8DSA7SueFfkTv-g.gif" /></figure><h3><strong>5. Advanced configuration</strong></h3><p>So far we’ve described a single agent running a single flow on a single device. That works, and it’s probably where you should start. But there are two main points for you to consider going further: how you orchestrate the agents doing the work and which models you assign to each job. They’re the difference between a test that takes ten minutes and costs a dollar and one that takes one minute and costs basically nothing.</p><h4><strong>5.1 Plan first, execute later</strong></h4><p>The instinct is to hand a test plan to one agent and let it handle everything. That works for a single flow, but it falls apart at scale. A single agent running six flows carries the plan, the dependencies, the screen states, and the evidence all in one context window, and it slows under the weight of it.</p><p>The fix is to split the work across different roles. The orchestrator reads the test plan and dispatches work according to the dependency table, never touching the simulator itself. Individual flows get handed off to executor agents, each one running a single flow in its own Appium session. Each executor reports back with a results table and screenshots for its single flow, and the orchestrator stitches them into a final summary. Because flows declare their dependencies, any two that share no edge in the graph can run in parallel across separate sessions.</p><h4><strong>5.2 Picking the right model for the job</strong></h4><p>Every decision in this system has a token budget attached, and the model you choose is the biggest line item. The trade-off is straightforward but easy to get wrong: lighter models are cheaper and faster, heavier models are smarter and more expensive. The trick is matching the model to the task.</p><p>For a small and simple test, a light model is the right call. It follows the steps in a flow spec literally, without improvising. The tool mapping in the skill means it doesn’t need to reason about which Appium function to call; it just looks up the table. It burns a low amount of tokens, executes quickly, and rarely goes wrong because the flow file leaves no room for interpretation. The risk is that when something does go off-script, a light model doesn’t adapt. It loops, reasoning at length toward a solution that a heavier model would reach in one attempt.</p><p>Heavy models are the opposite. They cost way more per flow, but they earn it back when things get ambiguous. A heavy model adapts to unpredictable situations and finds a solution fast. This makes heavy models ideal for flow generation and for complex test runs where the flow can deviate from the happy path frequently.</p><p>Choosing which model to use depends on the complexity of your task, there is no rule. It’s worth starting with lighter models and if you find yourself making too many corrections to the agents, switch to a better one.</p><h3><strong>6. Comparing with other solutions</strong></h3><p>There are other ways to do mobile testing, and this approach isn’t the right one for every situation. But it’s worth understanding what you give up with each alternative.</p><p>Traditional XCTest and Espresso tests are the gold standard for determinism. They compile with the app, run in-process, and execute faster than anything else. The problem is maintenance. Every UI refactor breaks them, and most teams don’t have the bandwidth to keep their E2E suite current. Tests become legacy code nobody touches until they fail on CI, at which point someone comments them out and moves on. Setting up an agent to parse their results is also non-obvious, requiring a separate pipeline step that extracts test reports, maps failures to screens, and feeds everything back into the AI’s context before it can verify whether the feature looks correct.</p><p>Then there’s the option of giving an agent no MCP at all, just telling it “test the login screen” and letting it figure things out. This fails most of the time. Without a way to boot the simulator, query the accessibility tree, or tap a target, the agent can only talk about testing in the abstract. It either asks you to do everything manually, or it burns tokens reasoning about how to test without ever actually testing. Either way, you’re the bridge between the agent and the app, which defeats the purpose.</p><p>What the flow-spec approach gives you that none of the others do is a single artifact that serves three purposes. It is documentation, an executable test the agent runs step by step, and a self-maintaining artifact that updates itself when a label drifts rather than failing silently. No other approach ties those three together in a markdown file that lives next to the code and costs nothing to version.</p><p>For most teams building mobile apps with AI, the flow-spec approach hits the right balance between determinism and adaptability. It won’t replace XCTest for performance benchmarks, but it is a good way of handing the AI the heavy work while you worry about more important things.</p><h3><strong>7. Caveats</strong></h3><p>No approach is free, and this one has costs worth being honest about. None of them are dealbreakers, but they’re the kind of thing you want to know before implementing.</p><h4><strong>7.1 Token usage</strong></h4><p>We covered this in the model selection section, but it’s worth repeating: every flow execution burns tokens. The mitigation is straightforward: choose the right model for each task, cache screen snapshots and locator dumps so the agent doesn’t re-discover the same screen twice, write good prompts and skills. With context and deterministic instructions the AI can worry only about executing the tests, no unnecessary reasoning at all.</p><h4><strong>7.2 Accessibility dependency</strong></h4><p>This is the structural cost: the entire system depends on your app having good accessibility labels. If your buttons don’t have labels, the agent can’t find them. If your labels are autogenerated gibberish, the agent finds the wrong thing.</p><p>There’s a temptation to sidestep this with a screenshot and coordinates approach (give the agent a screenshot, let it click at pixel, check the next screenshot for the result). This works at a certain level, but coordinates break the moment the UI changes. Besides, screenshot-based verification is slow because every assertion requires a vision model call. It’s non-deterministic by design, and it gets worse as your test suite grows.</p><p>Accessibility labels are the opposite. They’re deterministic (a button’s label is the same string regardless of screen size, theme, or OS version) and fast. They serve a purpose beyond testing: labels enable VoiceOver, Switch Control, and every other assistive technology on the platform. The investment you make in labeling for tests is the same investment that makes your app usable by people who rely on screen readers. That’s a rare case where the thing that makes your tests reliable also makes your product better for real users.</p><h4><strong>7.3 Non-determinism</strong></h4><p>An LLM interpreting a flow spec will occasionally see the same screen and make a different call. Maybe the timing was slightly different, the network hiccuped, the model just hallucinated. This is inherent to the technology and it’s not going away.</p><p>What you can do is shrink the surface area where non-determinism can appear. The <em>[expect: pass]</em> and <em>[expect: fail]</em> annotations mean the agent never has to decide whether a step was successful. The tool mapping means the agent never has to choose which Appium function to call. With these in place, non-determinism is mostly confined to the kind of edge case a heavy model handles better anyway. If a particular flow keeps failing intermittently, run it on a heavier model.</p><h4><strong>7.4 Maintainability</strong></h4><p>The test infrastructure still needs to evolve alongside the app. The <em>AGENTS.MD</em>, the skills, the flow specs, the suites. But this kind of maintenance is fundamentally different from what traditional tests demand. When a XCTest breaks because a button moved, you write code. When a flow spec breaks because a label changed, the agent writes a one-line diff. The files are versioned markdown next to your code, so they follow the same review process as everything else.</p><p>The real question is not whether files need maintenance. They always will. The question is whether maintaining them costs more than the bugs they catch. Traditional E2E tests often fail this math because the maintenance cost is high and the coverage is shallow. Flow specs invert it: maintenance is largely automated, and the coverage spans the primary user journey as well as the obscure failure states that manual testing usually misses.</p><h3><strong>8. Conclusion</strong></h3><p>AI agents can write mobile apps, but without a feedback loop they’re coding blind. The web has the DOM, which makes it easy to test. Mobile has a tangle of platform-specific accessibility trees, simulator toolchains that take an afternoon to set up, and no universal way to say “does this button work.”</p><p>What we built is a system where the answer to that question is a markdown file. The <em>AGENTS.MD</em> tells the agent what conventions the project follows. The test automation skill maps natural language actions to Appium MCP calls. The flow spec defines exactly what should happen. The flow generation skill writes those specs from your code. The test suite chains them together with dependencies. And a single command executes it all and returns a results table with screenshots. With that, you get deterministic mobile testing that survives layout changes, documents your features, and closes the loop between writing code and knowing it works.</p><p>Now, you are ready to let the agents coordinate your code writing and execution while you can refine your requirements to feed the AI with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5162a37f2526" width="1" height="1" alt=""><hr><p><a href="https://medium.com/profusion-engineering/automating-mobile-tests-with-ai-5162a37f2526">Automating mobile tests with AI</a> was originally published in <a href="https://medium.com/profusion-engineering">ProFUSION Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validating API requests on E2E tests using WDIO]]></title>
            <link>https://medium.com/profusion-engineering/validating-api-requests-on-e2e-tests-using-wdio-71e7bcaaae47?source=rss-68ff125aaa1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/71e7bcaaae47</guid>
            <category><![CDATA[automation-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[wdio]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[puppeteer]]></category>
            <dc:creator><![CDATA[Giulia Brocchi]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 18:34:56 GMT</pubDate>
            <atom:updated>2025-09-18T18:34:56.937Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever deployed your app to production and hours later realized that an API request was missing or incorrect? This might happen, for example, on analytics calls, that can be easily overlooked, or on really big projects, on which another team can mess up some parameters unintentionally. But don’t worry, end-to-end tests are a great solution to ensure that everything is working fine and you are firing your requests at the right time and using the correct data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*7VF-gSyygLYm3Jyd.jpg" /></figure><p>Not all solutions work for every test scenario due to the tool’s limitations or security measures. Because of that, we are going to explore some possibilities, so you can find the best method for your case.</p><p>For the examples, I’m going to use WebDriverIO (WDIO), which is a widely-used web automation framework that supports both Selenium and DevTools, and I’ll be evaluating the solutions using five different criteria (these are usually the ones that can cause you problems when trying to test the requests):</p><ol><li>Can capture API requests;</li><li>Can inspect data from request/response;</li><li>Works for requests made in page load phase;</li><li>Is actively maintained;</li><li>Works when running tests on cloud platforms.</li></ol><h3><strong>Intercepting the fetch method</strong></h3><p>If we are thinking of intercepting requests, let’s start with something simple. Why not replace the browser’s <em>fetch</em> function with our own? Then, we could add extra functionalities to validate the data.</p><p>Let’s try it. First, we need to keep a copy of the original fetch so we can call it at the end of our replacement function. Next, replace the fetch with a function that receives all the original arguments, validates them, and calls the original fetch — for the sake of brevity, we will skip validation and only add a console.log on the examples, but feel free to try your own implementations. It will look something like this:</p><pre>it(&#39;should intercept API calls&#39;, async () =&gt; {<br>  await browser.url(https://medium.com/&#39;my-website.com&#39;);<br><br>  await browser.execute(() =&gt; {<br>    const originalFetch = window.fetch;<br>    window.fetch = async (...args) =&gt; {<br>      console.log(args);<br><br>      return originalFetch.apply(this, args);<br>    };<br>  });<br><br>  const button = $(&#39;#my-button&#39;);<br><br>  await button.scrollIntoView();<br>  await button.click();<br>});</pre><p>Seems like it would work, right? Well… not quite. WebDriver (and tools like WDIO) runs injected scripts in a sandboxed execution environment. This is similar to how Chrome extensions run in an “isolated world”: you can see the DOM, but you don’t actually share the same JavaScript context as the page itself. So when you overwrite the fetch function, you’re only changing it in the automation’s context — which will not be useful to intercept the requests.</p><p>And finally, here’s how this solution stacks up against our five criteria:</p><ol><li>Can capture API requests ❌</li><li>Can inspect data from request/response ❌</li><li>Works for requests made in page load phase ❌</li><li>Is actively maintained ❌</li><li>Works when running tests on cloud platforms ❌</li></ol><h3><strong>Intercept Service</strong></h3><p>One major advantage of WDIO is the number of available plugins, so you can add some extra functionalities to your automated tests. The Intercept Service is one example, which under the hood overwrites the <em>fetch</em> and <em>XMLHTTPRequest</em> functions, but it is able to bypass the isolated test context.</p><p>To enable it, you need to first download the package and add it to the services array:</p><pre>npm install wdio-intercept-service -D</pre><pre>// wdio.conf.ts<br><br>export const config: WebdriverIO.Config = {<br>  // Other configs<br>  services: [<br>    // Other services<br>    &#39;intercept&#39;<br>  ],<br>};</pre><p>If you are using TypeScript, you can also add the types on <em>tsconfig</em>:</p><pre>// tsconfig.json<br><br>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;types&quot;: [<br>      // Other types<br>      &quot;wdio-intercept-service&quot;<br>    ]<br>  }<br>}</pre><p>Now, we have multiple ways of using this plugin to validate our requests. For example, you can use the <em>expectRequest</em> function to assert if your API was called at one specific endpoint and returned the expected status code:</p><pre>it(&#39;should intercept API calls&#39;, async () =&gt; {<br>  await browser.url(https://medium.com/&#39;my-website.com&#39;);<br>  browser.setupInterceptor();<br><br>  browser.expectRequest(&#39;POST&#39;,&#39;/my/api/route&#39;, 200);<br><br>  const button = $(&#39;#my-button&#39;);<br><br>  await button.scrollIntoView();<br>  await button.click();<br><br>  browser.disableInterceptor();<br>});</pre><p>In this example, we were able to validate if the request was successful, but it might not be enough. To validate extra request details — like the headers or body — we can use the <em>getRequests</em> function to get the list of all API calls and then make our own checks.</p><pre>it(&#39;should intercept API calls&#39;, async () =&gt; {<br>  await browser.url(https://medium.com/&#39;my-website.com&#39;);<br>  browser.setupInterceptor();<br><br>  const button = $(&#39;#my-button&#39;);<br><br>  await button.scrollIntoView();<br>  await button.click();<br>  await browser.pause(1000);<br>  const requests = await browser.getRequests();<br><br>  console.log(requests);<br><br>  browser.disableInterceptor();<br>});</pre><p>The snippet above shows that the intercept service works really well when we are testing calls made after a user interaction (like a button click). However, there are still some limitations. On the plugin’s official docs, it already mentions that API calls made during the page’s load phase will not be captured, simply because the service will be injected on the page after it’s fully loaded. Also, if the page is redirected right after the call, it might also not be able to catch them, so your tests will fail even though they were supposed to pass. It has also occurred to me — and some other GitHub users who raised issues on the plugin’s repository — that sometimes not all requests are captured, and you might end up with an empty array. The reason why this happens hasn’t been addressed yet, and neither fixed (in fact, the last update on the code was made in early 2024).</p><p>Despite the limitations and problems, this plugin might work for what you are looking for, but I don’t recommend using it, because, as we’ve seen, the project is no longer under support, and you might encounter more problems than solutions. In conclusion, we are starting to have some of our criteria met, but it’s not ideal yet:</p><ol><li>Can capture API requests ✅</li><li>Can inspect data from request/response ✅</li><li>Works for requests made in page load phase ❌</li><li>Is actively maintained ❌</li><li>Works when running tests on cloud platforms ✅</li></ol><h3><strong>WDIO BiDi protocol</strong></h3><p>Onto our next solution, let’s try to use something new. The WDIO BiDirectional (BiDi) protocol is an extension to the default protocol used to communicate with the browser. It adds some low-level functionalities that allow you to have more control over the test environment. Since it’s still under development, older browser versions might not support the protocol, so make sure to check before adding it.</p><p>First, you need to set webSocketUrl to true in your capabilities, like so:</p><pre>// wdio.conf.ts<br><br>export const config: WebdriverIO.Config = {<br>  // Other configs<br>  capabilities: [<br>    // Other capabilities<br>    webSocketUrl: true<br>  ],<br>};</pre><p>Now, we are ready to use all of BiDi’s functionalities. It doesn’t offer a direct way to assert if the requests were made like the intercept service, but it does allow you to capture requests in multiple ways. Let’s try with the <em>networkAddIntercept</em>. In this example, before even opening the page, we add the interceptor configured to stop the requests after they are completed. Then, we set a listener to execute every time a request is captured. After this initial setup, we finally open the page and perform some actions to complete the test.</p><pre>it(&#39;should intercept API calls&#39;, async () =&gt; {<br>  await browser.networkAddIntercept({<br>    phases: [&#39;responseCompleted&#39;],<br>    urlPatterns: [{ type: &#39;string&#39;, pattern: &#39;my-api-url.com/path&#39; }],<br>  });<br><br>  browser.on(&#39;network.responseCompleted&#39;, event =&gt; {<br>    console.log(event.request);<br>  });<br><br>  await browser.url(https://medium.com/&#39;my-website.com&#39;);<br><br>  const button = $(&#39;#my-button&#39;);<br><br>  await button.scrollIntoView();<br>  await button.click();<br>  await browser.pause(1000);<br>});</pre><p>And the result is… It works! We are able to capture all the requests, even those that are made during the page loading phase. It sounds too good to be true, right? That’s because we have other limitations. Due to security reasons, the BiDi protocol doesn’t expose the request and response bodies, it only returns their sizes as integers. So, if your intention is to validate the data sent or received by your API, unfortunately, this will not work. Even though you can use some other cool information that it returns, for example, the API call timings, which allows you to control the overall speed of your website.</p><p>We can also test some other BiDi functions, but the final output is always the same. If you want to try an example using the <em>mock</em> function to make the interceptor by hand, you can use this one (mind you, it has the same limitations listed above):</p><pre>it(&#39;should intercept API calls&#39;, async () =&gt; {<br>  const mock = await browser.mock(&#39;**&#39;);<br><br>  mock.on(&#39;request&#39;, ({ request }) =&gt; {<br>    console.log(request);<br>  });<br><br>  await browser.url(https://medium.com/&#39;my-sebsite.com&#39;);<br><br>  const button = $(&#39;#my-button&#39;);<br><br>  await button.scrollIntoView();<br>  await button.click();<br>  await browser.pause(1000);<br>});</pre><p>And our final score for the WDIO BiDi protocol:</p><ol><li>Can capture API requests ✅</li><li>Can inspect data from request/response ❌</li><li>Works for requests made in page load phase ✅</li><li>Is actively maintained ✅</li><li>Works when running tests on cloud platforms ✅</li></ol><h3><strong>Puppeteer</strong></h3><p>We still have one more tool to test, so we can meet all of our criteria and be able to successfully validate our requests without any limitations. Right off the bat, Puppeteer only supports Chromium-based browsers, so if you need to test Mozilla or Safari you can already skip this section. But let’s give it a try anyway, what do we have to lose?</p><p>It’s important to mention that Puppeteer is the current replacement for the Devtools on WDIO, which is being slowly deprecated. Some functions are not yet implemented, but we can already take advantage of the event listeners. So let’s go on and install our dependencies:</p><pre>npm install puppeteer-core<br><br># Also install the types if you are using TypeScript<br>npm install @types/puppeteer -D</pre><p>To start our tests, before opening the URL, we use the <em>getPuppeteer</em> function to get the Puppeteer instance and get our current working page. Then, we set a listener to the page requests, which will capture all API calls before they are sent, and we are free to proceed with the rest of the test.</p><pre>it(&#39;should intercept API calls&#39;, async () =&gt; {<br>  const puppeteer = await browser.getPuppeteer();<br>  const pages = await puppeteer.pages();<br>  const page = pages[0];<br><br>  page.on(&#39;request&#39;, request =&gt; {<br>    console.log(request.response());<br>  });<br><br>  await browser.url(https://medium.com/&#39;my-website.com&#39;);<br><br>  const button = $(&#39;#my-button&#39;);<br><br>  await button.scrollIntoView();<br>  await button.click();<br>  await browser.pause(1000);<br>});</pre><p>Surprisingly, Puppeteer can get all the request and response data, it captures requests even on the page load phase, and you are even able to return mocked responses. It would be the perfect solution if it weren’t for two major limitations. One we already talked about, it’s only available on Chromium-based browsers, and the other one is that it doesn’t work on cloud web automation platforms (like LambdaTest, Sauce Labs, or BrowserStack Automate) since they don’t expose the Devtools to be used by WDIO. Working with Puppeteer is perfect if you are testing Chromium browsers locally, so if this meets your needs, I highly recommend it since it’s the most reliable tool.</p><p>And our final criteria match:</p><ol><li>Can capture API requests ✅</li><li>Can inspect data from request/response ✅</li><li>Works for requests made in page load phase ✅</li><li>Is actively maintained ✅</li><li>Works when running tests on cloud platforms ❌</li></ol><h3><strong>Conclusion</strong></h3><p>Validating API requests in end-to-end tests is not a one-size-fits-all problem. Each approach comes with its strengths and limitations, and the right choice depends heavily on your project’s requirements and environment.</p><p>If your goal is broad compatibility and cloud support, BiDi is currently your best option. If you need deep inspection of request and response data and you’re fine with local Chromium testing, Puppeteer is the way to go. I would not recommend the intercept service since it’s not maintained anymore, but if it’s the only option that fits your needs, go for it.</p><p>In the end, there’s no “right” solution, but by understanding the trade-offs of each tool, you can choose the setup that ensures your API requests are validated, your tests remain stable, and your deployments are more reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71e7bcaaae47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/profusion-engineering/validating-api-requests-on-e2e-tests-using-wdio-71e7bcaaae47">Validating API requests on E2E tests using WDIO</a> was originally published in <a href="https://medium.com/profusion-engineering">ProFUSION Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>