LogoLogo
🚀 Run Maestro tests in the cloud →
  • Home
  • Star us on GitHub
  • Getting Started
    • What is Maestro?
    • Installing Maestro
      • macOS
      • Windows
      • Linux
    • Build and Install your App
      • Android
      • iOS
    • Run a Sample Flow
    • Writing Your First Flow
    • Maestro Studio
    • Running Flows on CI
  • Cloud
    • Run Maestro tests in the cloud
    • Cloud Quickstart
    • CI Integration
      • GitHub Actions
        • Maestro GitHub Action for Android
        • Maestro GitHub Action for iOS
        • Maestro GitHub Action for Flutter
      • Bitrise
      • Bitbucket Pipelines
      • CircleCI
      • Integration with any CI platform
    • Pull Request Integration
    • Cloud Reference
      • Build your app for the cloud
      • Configuring OS Version
      • Configuring device locale
      • Device timezones
      • Email Notifications
      • Slack Notifications
      • Webhook Integration
      • Managing Secrets
      • Limits
      • Reusing App Binary
      • IP Allowlist
      • System Status
  • Platform Support
    • Supported Platforms
    • Android - Views
    • Android - Jetpack Compose
    • iOS - UIKit
    • iOS - SwiftUI
    • React Native
    • Flutter
    • Web Views
    • Web (Desktop Browser)
  • Examples
    • Android contacts flow automation
    • Facebook signup flow automation
    • Advanced: Wikipedia Android
    • Page Object Model
  • CLI
    • Cloud
    • Test Suites & Reports
    • Tags
    • Record Your Flow
    • Continuous Mode
    • View Hierarchy
    • Start Device
  • API Reference
    • Commands
      • addMedia
      • assertVisible
      • assertNotVisible
      • assertTrue
      • assertWithAI
      • assertNoDefectsWithAi
      • back
      • clearKeychain
      • clearState
      • copyTextFrom
      • evalScript
      • eraseText
      • extendedWaitUntil
      • extractTextWithAI
      • hideKeyboard
      • inputText
      • killApp
      • launchApp
      • openLink
      • pressKey
      • pasteText
      • repeat
      • retry
      • runFlow
      • runScript
      • scroll
      • scrollUntilVisible
      • setAirplaneMode
      • setLocation
      • startRecording
      • stopApp
      • stopRecording
      • swipe
      • takeScreenshot
      • toggleAirplaneMode
      • tapOn
      • doubleTapOn
      • longPressOn
      • travel
      • waitForAnimationToEnd
    • Common command arguments
    • Selectors
    • Configuration
      • Workspace configuration
      • Flow configuration
      • AI configuration
  • Advanced
    • Nested Flows
    • Wait
    • Loops
    • Conditions
    • Parameters & Constants
    • JavaScript
      • Run JavaScript
      • Outputs
      • Logging
      • Access element text
      • Make HTTP requests
      • GraalJS support
      • JavaScript announcement blog
    • Specify a Device
    • Configure Permissions
    • Detect Maestro in your app
    • Configure Maestro driver timeout
    • onFlowStart / onFlowComplete hooks
    • Test in different locales
    • Structuring your test suite
  • Troubleshooting
    • Known Issues
    • Frequently Asked Questions
    • Bug Report
    • Rollback Maestro
    • Debug Output
    • HOWTOs
      • Arrange your repository for Maestro tests
      • scrollUntilVisible for fragments
  • Community
    • Contributions
    • Articles & Tutorials
    • Case Studies
    • Resources
Powered by GitBook

Read to wire into CI or scale up your testing?

  • Run Maestro tests in the cloud →
On this page
  • JSON
  • POST request
  • Headers
  • Other request types
  • Response object
  • Example
  • Shared Functions
  • Additional Information

Was this helpful?

Edit on GitHub
  1. Advanced
  2. JavaScript

Make HTTP requests

Maestro comes with its own JavaScript HTTP API

// script.js
const response = http.get('https://example.com')

output.script.result = response.body

JSON

Use json() function to parse JSON responses.

For example, assume that https://example.com/jsonEndpoint returns the following result:

{
    "myField": {
        "mySubField": "Test value"
    }
}

mySubField could then be accessed in the following way:

// script.js
const response = http.get('https://example.com/jsonEndpoint')

output.script.result = json(response.body).myField.mySubField

POST request

To send body to a given endpoint, specify a body parameter:

// script.js
const response = http.post('https://example.com/myEndpoint', {
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(
        {
            myField: "Payload"
        }
    )
})

You can also send multipart form data by specyfying multipartForm parameter:

// script.js
const response = http.post('https://example.com/myEndpoint', {
    multipartForm: {
      "uploadType": "import",
      "data": {
        "filePath": filePath,
        "mediaType": "text/csv"
      }
    },
})

In multipartForm you can include many fields. It is also possible to upload multiple files in one request by using objects with filePath property. filePath is required for the files. mediaType is optional.

â„šī¸ Note If you include both body and multipartForm in one request then body will be ignored.

Headers

Headers can be provided in a headers parameter

// script.js
const response = http.get('https://example.com', {
    headers: {
        Authorization: 'Bearer MyToken'
    }
})

Other request types

The following request methods are provided out of the box:

  • http.get

  • http.post

  • http.put

  • http.delete

To send a request of any other HTTP method, use http.request

// script.js
const response = http.request('https://example.com`, {
    method: "GET"   // or specify any other method, i.e. OPTION
})

Response object

Field Name
Value

ok

true if request was successful, false otherwise

status

HTTP status code (i.e. 200)

body

String body of the response

headers

response HTTP headers, where each header value is a string (or a comma-separated string in case of multiple values)

Example

Here's an example of using these utilities to perform a common test action, creating a user and populating it with data.

const date = new Date();
const email = `test${date.getTime().toString()}@test.com`;
const password = 'test'

function createNewUser() {
  const url = 'https://my-api/signup'

  const signupResponse = http.post(url, {
    body: JSON.stringify({
      email: email,
      password: 'test'
    }),
    headers: {'Content-Type': 'application/json'}
  });

  const data = json(signupResponse.body);

  return {
    guid: data.guid,
    token: data.token
  }
}

function fillUserInfo() {
  const test_user = createNewUser()
  const url = `https://my-api/user/${test_user.guid}`

  http.request(url, {
    method: 'PATCH',
    body: JSON.stringify({
      age: '46',
      gender: 'female',
      country: 'Canada'
    }),
    headers: {
      'Content-Type': 'application/json', 
       Authorization: test_user.token,
      }
  })

  // return email and password for logging in to newly created account
  return {
    email: email,
    password: password
  }

}

output.test_user = fillUserInfo()

Shared Functions

The output object in JavaScript can hold functions as well as values and JSON objects. You can use this to put all of your bespoke API calls into the output object, and call them from elsewhere in your flow.

api.js:

function createUser(username) {
  return http.post("https://my-api/register", {
    body: {
      "username": username,
      "name": "Test User"
    }
  })
}


function getUserHistory(username) {
  return http.get("https://my-api/users/" + username + "/history")
}

output.api = {
  createUser,
  getUserHistory
}

flow.yaml:

appId: com.example
onFlowStart:
  - runScript: ./util/api.js
---
- launchApp
- evalScript: ${output.createUser('myTestUser')}
- tapOn: 'username'
- inputText: 'myTestUser'

Additional Information

For test developers looking for additional information on the API, and the structure of objects, the Maestro implementation is a wrapper around okhttp3.

PreviousAccess element textNextGraalJS support

Last updated 2 months ago

Was this helpful?

Setting a 'Content-Type' header might be required. See .

Headers