Exit course
Chapter 4 of 10 Beginner 7 min read 3 quick checks Updated

Subflows, Conditions, Loops and JavaScript

On this page
  1. Subflows with runFlow
  2. Variables: env, -e and defaults
  3. Conditions with when
  4. Loops and retries
  5. JavaScript
  6. Putting it together
  7. Hooks for setup and teardown

A suite of twenty flows that each copy the same login steps is twenty places to fix when the login screen changes. This chapter covers the tools Maestro gives you to avoid that: subflows, variables, conditions, loops, retries and JavaScript. Every snippet in the worked example below was run against the sample app on an iOS simulator.

Subflows with runFlow#

Move repeated steps into their own file and call it with runFlow. Paths are relative to the calling flow. Keep subflows in a subfolder: when you run maestro test ., Maestro only picks up flow files at the top level of the folder, so files in subflows/ are not executed on their own.

flows/
  add_numbers.yaml
  table.yaml
  subflows/
    enter_numbers.yaml
  scripts/
    expected.js

subflows/enter_numbers.yaml types two values into the calculator. It reads them from variables, so the caller decides the data:

appId: org.reactjs.native.example.SampleApp
---
- tapOn:
    id: inputA
    point: "90%,50%"
- eraseText
- inputText: ${A}
- tapOn:
    id: inputB
    point: "90%,50%"
- eraseText
- inputText: ${B}

Variables: env, -e and defaults#

Variables use ${NAME} syntax and are case-sensitive. There are three common sources:

  • The flow header. An env: block above --- defines constants for that flow and the subflows it calls.
  • The command line. maestro test -e A=7 -e B=8 table.yaml. CLI values are always strings; parse them in JavaScript if you need numbers.
  • The runFlow call. Pass values to one subflow invocation:
- runFlow:
    file: subflows/login.yaml
    env:
      USERNAME: "admin@example.com"

Constants defined in a subflow, in its header or in the runFlow call, override parameters with the same name from the parent. To make a subflow usable on its own, give it a default with a JavaScript expression: ${USERNAME || "guest"}.

The Maestro CLI also exposes shell environment variables that start with MAESTRO_ (for example MAESTRO_API_KEY) to your flows, which is convenient in CI. Built-in variables include MAESTRO_FILENAME and, when sharding, MAESTRO_SHARD_INDEX.

In CI you export API_KEY=... in the shell, but ${API_KEY} is empty inside the flow. Why?

The CLI passes through MAESTRO_-prefixed environment variables only. Anything else has to be passed explicitly with -e KEY=VALUE.

Conditions with when#

runFlow accepts a when block. If the condition is true, the file or inline commands run; otherwise they are skipped and the flow continues. The conditions are:

Condition Runs when
visible: an element matching the selector is on screen
notVisible: no matching element is on screen
platform: the platform is Android, iOS or Web
true: a JavaScript expression is true

Several conditions in one when must all hold. The classic use is a dialog that sometimes appears:

- runFlow:
    when:
      visible: "Rate this app"
    commands:
      - tapOn: "Not now"

For a single optional step there is a shorter form: add optional: true to the command, ideally with a label explaining why. Use conditions sparingly. A flow full of branches is hard to read, and a visible: check on an element that appears late can make the branch itself flaky. If two scenarios differ a lot, write two flows.

Loops and retries#

repeat runs commands a fixed number of times, while a condition holds, or both (whichever limit is hit first):

- repeat:
    times: 10
    while:
      notVisible: "End of list"
    commands:
      - scroll

retry re-runs a block if it fails, up to maxRetries (0 to 3, default 1):

- retry:
    maxRetries: 2
    commands:
      - tapOn: "Refresh"
      - assertVisible: "Updated just now"

Treat retry as a scalpel. Wrapping a whole flow in it hides real defects, such as a button that only works half the time.

A repeat block has times: 10 and while: { notVisible: "End of list" }. When does it stop?

With both set, whichever limit is hit first ends the loop, so times works as a safety cap on the condition.

JavaScript#

Maestro embeds a JavaScript engine for logic YAML cannot express. There are three ways in:

  • Inline expressions, anywhere a value is accepted: - inputText: ${'user_' + Date.now()}.
  • evalScript for a one-line statement with no UI action: - evalScript: ${output.counter = 0}.
  • runScript for a .js file. Pass it values with env: just like a subflow.

Scripts share data through the global output object; anything you assign to it is readable later in the flow as ${output.name}. console.log writes to maestro.log (only the first argument is printed, so concatenate). The built-in http client (http.get, http.post, ...) and json() parser let a script create test data through your API instead of through the UI, and faker generates random names, emails and numbers.

scripts/expected.js computes the sum the app should show:

output.expected = String(parseInt(A) + parseInt(B))

Putting it together#

table.yaml uses all of the above against the sample app:

appId: org.reactjs.native.example.SampleApp
tags:
  - regression
env:
  A: ${A || "7"}
  B: ${B || "8"}
---
- launchApp
- runFlow:
    file: subflows/enter_numbers.yaml
- runScript: scripts/expected.js
- assertVisible: ${output.expected}
- runFlow:
    when:
      platform: Android
    commands:
      - hideKeyboard
- retry:
    maxRetries: 2
    commands:
      - assertVisible:
          id: sum
- copyTextFrom:
    id: sum
- assertTrue: ${maestro.copiedText == output.expected}

What happens when it runs:

  1. The env block sets A and B to 7 and 8 unless they were passed in, and the subflow sees them and types them.
  2. The script computes "15" into output.expected, and the assertion waits for that text.
  3. On iOS the Android-only block is reported as SKIPPED. (Why Android-only? See chapter 5: hideKeyboard could not dismiss the iOS number pad.)
  4. copyTextFrom reads the Total field into maestro.copiedText, and assertTrue compares it with the computed value.

Run it with different data without touching the file:

maestro test -e A=20 -e B=22 table.yaml   # types 20 and 22, expects 42

The ${A || "7"} form is deliberate. In our test run, a plain constant in the header (A: "7") won over -e A=20: the flow still typed 7. If a value should be overridable from the command line, give it a default with || instead of a fixed constant.

Hooks for setup and teardown#

Instead of starting every flow with the same runFlow, declare it once per flow as a hook in the header:

appId: com.example.app
onFlowStart:
  - runFlow: subflows/login.yaml
onFlowComplete:
  - runFlow: subflows/logout.yaml
---
- tapOn: "Profile"

onFlowComplete runs whether the flow passed or failed, which makes it the right place for cleanup such as deleting test data through your API. Keep hooks fast; they run for every flow.

When you later run these flows on TestingBot's Maestro grid, variables are passed with the same -e KEY=VALUE form, and secrets get a dedicated flag. The Maestro options reference lists both. Next: the differences between iOS and Android that your flows need to handle.

Your flow creates a user through the API and must delete it again, even when an assertion fails halfway. Where does the delete go?

onFlowComplete runs whether the flow passed or failed. The last command never runs after a failure, and relying on the next flow creates an order dependency.