Skip to navigation

Variables and control flow, written as tests

Each example on this page shows one procedure as prose, detected tests, inline tests, and a standalone spec. For what each tab holds, see Navigation and interaction.

Call an API with a token from an environment file

This procedure uses loadVariables and httpRequest, with the step fields variables and assertions, the jq() function, and publicVariables on the test and the spec.

The example folder holds the api.env file the steps load:

api.env
API_URL=http://localhost:8092/api
API_TOKEN=docs-example-token
prose.md
# Create an account with an API token
Keep the API address and your token in an `api.env` file next to this page:
```text
API_URL=http://localhost:8092/api
API_TOKEN=your-api-token
```
1. Load the variables from your `api.env` file.
2. Send a `POST` request to `$API_URL/accounts` with the header `Authorization: Bearer $API_TOKEN` and this body:
```json
{"name": "Wren", "plan": "team", "seats": 5, "roles": ["admin", "billing"]}
```
The API returns status `200` and the new account, with `plan` set to `team`. Note the account's `name`, its `seats`, and its first role.
3. Look up the account. Send a `GET` request to `$API_URL/accounts?name=<name>&seats=<seats>&role=<role>`. The response shows the same name, seat count, and role.

How the values flow

  • $API_URL and $API_TOKEN come from the api.env file. Doc Detective substitutes them into the URL and the Authorization header.
  • The first request’s variables field sets ACCOUNT_NAME from $$response.body.name, and ACCOUNT_SEATS from jq($$response.body, ".seats"). It sets ACCOUNT_ROLE from $$response.body.roles[0], the first item of the roles array. The second request uses all three in its URL, and its assertion reads $ACCOUNT_SEATS too.
  • assertions adds custom checks to a step. Each check is an expression over the step’s $$outputs, given as one string or as an array whose checks must all pass.
  • Doc Detective masks every value it loads or substitutes as ***NAME*** in logs and reports. publicVariables lists the names to show: ACCOUNT_* on the test, and API_URL on the spec. A name listed in the config, any spec, or any test is public for the whole run. See Keep secrets out of logs.

What detection finds

The prose has no links, bold text, or HTTP code blocks, so detection finds no steps. All three steps come from step statements.

The detected run also loads the api.env file before any test starts. The example’s own doc-detective.json sets the config-level loadVariables field, and lists API_URL in the config-level publicVariables:

doc-detective.json
{
"detectSteps": true,
"loadVariables": "api.env",
"publicVariables": ["API_URL"]
}

A config-level file only fills variables that aren’t already set, while a loadVariables step replaces them.

Check your Node.js version

This procedure uses runShell, the step and test if conditions, the extract() function, and the onSkip and onFail step routing entries continue and stop.

prose.md
# Check your Node.js version
1. Print the Node.js version:
```shell
node --version
```
The output starts with `v` and the major version, such as `v22.11.0`. You need version 18 or later.
2. If Node.js printed a version, print the npm version:
```shell
npm --version
```
3. Find the Node.js executable. On Windows, run:
```shell
where node
```
On macOS and Linux, run:
```shell
command -v node
```

How the conditions work

  • The test’s if runs the test only on Linux, macOS, and Windows. The standalone spec sets the same condition on the spec. Both give if as an array, whose conditions must all be true. A string if holds a single condition, as on the test in the API example and the spec in the next example. A false condition skips the spec, test, or step it’s on.
  • The first step’s variables field sets NODE_MAJOR from extract($$stdio.stdout, "v([0-9]+)"), the major version in the command’s output. Its assertion checks the output with matches.
  • The second step runs only when both conditions in its if array hold: the first step exited 0 and its output starts with v. $$steps.node-version.outputs reads an earlier step’s output by its stepId. Its assertion $NODE_MAJOR >= 18 substitutes the variable the first step set.
  • The last two steps check $$platform, so each platform runs one of them and skips the other. onSkip with continue: true moves on after the skip, which is also the default. onFail with stop: "test" stops the test’s remaining steps, which is also the default for a failure.

What detection finds

The commands sit in shell code blocks, and default detection turns only bash, Python, and JavaScript code blocks into steps, so detection finds none here. Every step comes from a step statement, and the detected and inline variants differ only in detectSteps.

Wait for a service, then echo text through it

This procedure has three tests. It uses wait, runShell, goTo, click, type, find, and httpRequest. It routes with the step routing entries retry and goToStep, and the test routing entries goToTest, stop: "spec", and continue. Several routing entries carry an if condition, as a string or an array. It also sets the context field retries.

prose.md
# Echo text through the service
## Check that the service is ready
The service can take a few seconds to start, so wait five seconds before you check it.
Check that the service is ready. If the check fails, check again after a short wait:
```shell
node -e "const fs=require('fs'),f=require('path').join(require('os').tmpdir(),'doc-detective-docs-ready');if(fs.existsSync(f)){fs.rmSync(f)}else{fs.writeFileSync(f,'');console.error('Not ready yet.');process.exit(1)}"
```
This example simulates a service that isn't ready the first time you check.
## Restart the service
If the service still isn't ready, restart it:
```shell
node -e "console.log('Restarting the service.')"
```
## Echo text
1. Go to [the type echo page](http://localhost:8092/type-echo.html).
2. Click **Type here:**.
3. Type "Hello, Doc Detective".
4. Check that the page shows **Hello, Doc Detective** below the field. If it doesn't, type the text again.
5. Send the text to the messages API. Send a `POST` request to `http://localhost:8093/api/messages` with this body:
```json
{"text": "Hello, Doc Detective"}
```
The API returns the same text.

How the routing works

First, wait: true pauses for 5000 milliseconds, the default for wait. A number sets the pause in milliseconds instead.

The readiness check then fails on purpose the first time it runs, and the test still passes:

  1. The check exits 1 and prints Not ready yet.
  2. Its onFail entry applies only when $$outputs.exitCode == 1, so a different exit code falls through to the default and stops the test. The entry’s retry runs the check again after 500 milliseconds, up to 3 more times, with exponential backoff between runs.
  3. The second run exits 0, so the step passes. Its result reports "attempts": 2.

A step that a retry brings back to passing counts as passed. Other routing doesn’t change a result: a step that fails and then routes with continue or goToStep still fails its test.

The rest of the routing:

  • The first test’s onPass entry goToTest jumps to data-echo-text, so data-service-restart doesn’t run and doesn’t appear in the results. If the check still fails after its retries, the onFail entry stop: "spec" skips the spec’s remaining tests. A test routing entry’s if reads $$platform. Here it’s an array on onPass and a string on onFail, and both are true on every supported platform.
  • In data-echo-text, the read-echo step saves the element’s text from $$element.text. When it passes and its text matches the if array of its onPass entry, goToStep jumps over the retype step to send-echo. When it fails, retry runs it again.
  • send-echo runs only when $$steps.read-echo.outputs.element.text matches, sends the saved $ECHOED value, and asserts that the response echoes it. The test’s publicVariables shows ECHOED in output instead of masking it.
  • onWarning with continue: true, on send-echo and on the test, moves on after a warning, which is also the default. The test’s onSkip entry stop: "spec" skips the spec’s remaining tests if Doc Detective skips this test.
  • The context’s retries: 2 runs the whole test again on a fresh browser session, up to twice, when the session crashes or never loads a page. A real failure, such as a missing element, doesn’t trigger it. A step’s retry runs one step again on the same session.

A step that retry or goToStep runs more than once reports attempts or visit in its result. A test that goToTest runs again reports visit. Doc Detective sets these fields. Don’t set them in a test.

What detection finds

In the first two tests, the commands sit in shell code blocks, which default detection doesn’t run, so their steps come from step statements.

In data-echo-text, detection resolves the prose to six steps:

ProseDetected steps
Go to a linkgoTo the URL, then checkLink the same URL
Click a bold phraseclick the phrase, then find the same phrase
type "…"type the quoted text
A bold phrasefind the phrase

A step statement adds the httpRequest, which sends the literal text because no detected step saves it. The detected data-echo-text has no retype step or step routing: those live on steps that only the inline and standalone variants write out.

About the permutations

Each example below varies one setting in a short procedure. Detection finds no steps in these procedures, because the URLs and commands sit in code. So every variant runs the same step statements, and the detected and inline files differ only in detectSteps.

For onPass, onFail, onWarning, and onSkip, see Step routing and Test routing.

loadVariables permutations

Step, file next to the test

Varies: step.loadVariables · Value: "service.env" · Effect: the step loads service.env from the test file’s folder, and later steps substitute $SERVICE_URL.

prose.md
# Check a service from an environment file
1. Load the variables in `service.env`.
2. Check the service. Send a `GET` request to `$SERVICE_URL/health`.

Step, file in a child folder

Varies: step.loadVariables · Value: "env/service.env" · Effect: a relative path resolves from the test file’s folder, so the step loads env/service.env below it.

prose.md
# Check a service from an environment file in a child folder
1. Load the variables in `env/service.env`.
2. Check the service. Send a `GET` request to `$SERVICE_URL/health`.

In the config file

Varies: config.loadVariables · Value: "service.env" · Effect: the example’s doc-detective.json loads the file before any test runs, so no step loads it. A relative path resolves from the config file’s folder.

prose.md
# Check a service with variables from the config
1. Check the service. Send a `GET` request to `$SERVICE_URL/health`.

variables expression permutations

$$response

Varies: step.variables · Value: {"ORDER_ID": "$$response.body.id"} · Effect: saves a field of the HTTP response body, and the next request sends it as a query parameter.

prose.md
# Create an order and look it up
1. Create an order. Send a `POST` request to `http://localhost:8092/api/orders` with this body:
```json
{"id":"ord-1001"}
```
2. Look up the order. Send a `GET` request to `http://localhost:8092/api/orders?id=<id>`.

$$stdio

Varies: step.variables · Value: {"NODE_VERSION": "$$stdio.stdout"} · Effect: saves the command’s output, and the next command reads it from its environment.

prose.md
# Save the Node.js version
1. Print the Node.js version:
```shell
node --version
```
2. Check that the saved version starts with `v`:
```shell
node -e "process.exit(process.env.NODE_VERSION.startsWith('v') ? 0 : 1)"
```

$$element

Varies: step.variables · Value: {"ECHOED": "$$element.text"} · Effect: saves the text of the element find matched, and the request sends it in its body.

prose.md
# Send the text a page shows
1. Open `http://localhost:8092/type-echo.html`.
2. Type `Wren` in the field.
3. Check that the page shows `Wren` below the field.
4. Send the text in a `POST` request to `http://localhost:8093/api/names`. The API returns it.

extract()

Varies: step.variables · Value: {"NODE_MAJOR": "extract($$stdio.stdout, \"v([0-9]+)\")"} · Effect: saves the first group in the regular expression, the major version number.

prose.md
# Save the Node.js major version
1. Print the Node.js version:
```shell
node --version
```
2. Check that the major version is a number:
```shell
node -e "process.exit(/^[0-9]+$/.test(process.env.NODE_MAJOR) ? 0 : 1)"
```

jq()

Varies: step.variables · Value: {"ITEM_COUNT": "jq($$response.body, \".items | length\")"} · Effect: saves the result of a jq query on the response body, the number of items.

prose.md
# Count the items in a cart
1. Create a cart. Send a `POST` request to `http://localhost:8092/api/carts` with this body:
```json
{"items":[{"sku":"A1","qty":2},{"sku":"B2","qty":1}]}
```
2. Send the count in a `GET` request to `http://localhost:8092/api/carts?count=<count>`.

Array index

Varies: step.variables · Value: {"FIRST_SKU": "$$response.body.items[0].sku"} · Effect: [0] picks the first item of an array in the response body.

prose.md
# Look up the first item in a cart
1. Create a cart. Send a `POST` request to `http://localhost:8092/api/carts` with this body:
```json
{"items":[{"sku":"A1","qty":2},{"sku":"B2","qty":1}]}
```
2. Look up the first item. Send a `GET` request to `http://localhost:8092/api/products?sku=<sku>`.

$VAR substitution permutations

In httpRequest.url

Varies: httpRequest.url · Value: "$SHOP_URL/products" · Effect: doc Detective replaces $SHOP_URL in the URL before it sends the request.

prose.md
# List products from a configured URL
1. Load the variables in `shop.env`.
2. List the products. Send a `GET` request to `$SHOP_URL/products`.

In httpRequest.request.headers

Varies: httpRequest.request.headers · Value: {"X-Test": "$SHOP_CLIENT"} · Effect: the header carries the variable’s value, and the echo API returns it in x-echo-test.

prose.md
# Send a client name in a header
1. Load the variables in `shop.env`.
2. Send a `GET` request to `http://localhost:8092/api/products` with the header `X-Test: $SHOP_CLIENT`.

In httpRequest.request.body

Varies: httpRequest.request.body · Value: {"client": "$SHOP_CLIENT"} · Effect: the body carries the variable’s value, and the echo API returns it.

prose.md
# Send a client name in a request body
1. Load the variables in `shop.env`.
2. Send a `POST` request to `http://localhost:8092/api/orders` with the body `{"client": "$SHOP_CLIENT"}`.

In type.selector and find.selector

Varies: type.selector and find.selector · Value: "$INPUT_SELECTOR" · Effect: selectors take variables too, so one file can name the elements for several tests.

prose.md
# Type into a field named by a variable
1. Load the variables in `shop.env`.
2. Open `http://localhost:8092/type-echo.html`.
3. Type `Wren` in the field.
4. Check that the page shows `Wren`.

publicVariables permutations

Test, exact name

Varies: test.publicVariables · Value: ["SHOP_URL"] · Effect: reports show the value of SHOP_URL, and mask SHOP_CLIENT and the selectors as ***NAME***.

prose.md
# List products and show the URL in reports
1. Load the variables in `shop.env`.
2. List the products. Send a `GET` request to `$SHOP_URL/products`.

Test, wildcard

Varies: test.publicVariables · Value: ["SHOP_*"] · Effect: * matches any characters, so reports show SHOP_URL and SHOP_CLIENT.

prose.md
# List products and show the URL in reports
1. Load the variables in `shop.env`.
2. List the products. Send a `GET` request to `$SHOP_URL/products`.

Spec

Varies: spec.publicVariables · Value: ["SHOP_URL"] · Effect: only the standalone spec can set it. A name listed on any spec is public for the whole run.

prose.md
# List products and show the URL in reports
1. Load the variables in `shop.env`.
2. List the products. Send a `GET` request to `$SHOP_URL/products`.

In the config file

Varies: config.publicVariables · Value: ["SHOP_URL"] · Effect: the example’s doc-detective.json lists the name, so every file in the run shows it.

prose.md
# List products and show the URL in reports
1. Load the variables in `shop.env`.
2. List the products. Send a `GET` request to `$SHOP_URL/products`.

if permutations

Step, string, true

Varies: step.if · Value: "$$steps.version.outputs.exitCode == 0" · Effect: the condition reads an earlier step’s output by its stepId. It’s true, so the step runs.

prose.md
# Print the npm version after Node.js
1. Print the Node.js version:
```shell
node --version
```
2. If that worked, print the npm version:
```shell
npm --version
```

Step, string, false

Varies: step.if · Value: "$$steps.version.outputs.exitCode != 0" · Effect: the condition is false, so Doc Detective skips the step. The test still passes.

prose.md
# Show help only when Node.js fails
1. Print the Node.js version:
```shell
node --version
```
2. If that failed, print the help for `node`:
```shell
node --help
```

Step, array

Varies: step.if · Value: ["$$steps.version.outputs.exitCode == 0", "$$steps.version.outputs.stdio.stdout matches /^v/"] · Effect: every condition in the array must be true for the step to run.

prose.md
# Print the npm version after a valid Node.js version
1. Print the Node.js version:
```shell
node --version
```
2. If that printed a version, print the npm version:
```shell
npm --version
```

Test, string

Varies: test.if · Value: "$$platform oneOf [linux, mac, windows]" · Effect: the test runs only when the condition is true. A test condition can read $$platform.

prose.md
# Check the API on desktop platforms
1. Check the API. Send a `GET` request to `http://localhost:8092/api/health`.

Test, array

Varies: test.if · Value: ["$$platform oneOf [linux, mac, windows]"] · Effect: the array form takes one or more conditions, and all must be true.

prose.md
# Check the API on desktop platforms
1. Check the API. Send a `GET` request to `http://localhost:8092/api/health`.

Test, by platform

Varies: test.if · Value: "$$platform == windows" · Effect: the test runs on Windows and is skipped on macOS and Linux.

prose.md
# Find Node.js on Windows
1. On Windows, find the Node.js executable:
```shell
where node
```

Spec, string

Varies: spec.if · Value: "$$platform oneOf [linux, mac, windows]" · Effect: only the standalone spec can set it. When it’s false, Doc Detective skips the whole spec.

prose.md
# Check the API on desktop platforms
1. Check the API. Send a `GET` request to `http://localhost:8092/api/health`.

Spec, array

Varies: spec.if · Value: ["$$platform oneOf [linux, mac, windows]"] · Effect: only the standalone spec can set it. Every condition must be true for the spec to run.

prose.md
# Check the API on desktop platforms
1. Check the API. Send a `GET` request to `http://localhost:8092/api/health`.

assertions permutations

String

Varies: step.assertions · Value: "$$outputs.response.statusCode == 200" · Effect: one custom check runs after the request’s own checks, and the step fails if it’s false.

prose.md
# Create an account and check the status
1. Create an account. Send a `POST` request to `http://localhost:8092/api/accounts` with this body:
```json
{"name":"Wren","plan":"team"}
```

Array

Varies: step.assertions · Value: ["$$outputs.response.statusCode == 200", "$$outputs.response.body.plan == \"team\""] · Effect: every check in the array must pass.

prose.md
# Create an account and check the response
1. Create an account. Send a `POST` request to `http://localhost:8092/api/accounts` with this body:
```json
{"name":"Wren","plan":"team"}
```

Comparison operators

Varies: step.assertions · Value: ==, !=, >, <, >=, <= · Effect: each operator compares the status code with a number.

prose.md
# Check the status code range
1. Create an account. Send a `POST` request to `http://localhost:8092/api/accounts` with this body:
```json
{"name":"Wren","plan":"team"}
```

Word operators

Varies: step.assertions · Value: contains, oneOf, matches · Effect: contains checks a substring, oneOf checks a list, and matches checks a regular expression.

prose.md
# Check the account fields
1. Create an account. Send a `POST` request to `http://localhost:8092/api/accounts` with this body:
```json
{"name":"Wren","plan":"team"}
```

Context retries permutations

retries: 0

Varies: context.retries · Value: 0 · Effect: turns off context retries, so a crashed browser session fails the test at once.

prose.md
# Echo a name on a page
1. Open `http://localhost:8092/type-echo.html`.
2. Type `Wren` in the field.
3. Check that the page shows `Wren`.

retries: 2

Varies: context.retries · Value: 2 · Effect: runs the test again on a fresh browser session, up to twice, if the session crashes or never loads a page. A missing element isn’t retried.

prose.md
# Echo a name on a page
1. Open `http://localhost:8092/type-echo.html`.
2. Type `Wren` in the field.
3. Check that the page shows `Wren`.