Write a Test (JS)

To write an Appium test in JavaScript (Node.js), we need to choose an Appium-compatible client library. The best-maintained library and the one the Appium team recommends using is WebdriverIO, so let's use that. Since we already have Appium installed we know our Node and NPM requirements are already satisfied. So just create a new project directory somewhere on your computer and then initialize a new Node.js project in it:

npm init

It doesn't really matter what you put in the prompts, just so long as you end up with a valid package.json.

Now, install the webdriverio package via NPM:

npm i --save-dev webdriverio

Once this is done, your package.json file should include a section like the following:

package.json
{
  "devDependencies": {
    "webdriverio": "8.31.1"
  }
}

Now it's time to type up the test itself. Create a new file called test.js with the following contents:

test.js
const {remote} = require('webdriverio');

const capabilities = {
  platformName: 'Android',
  'appium:automationName': 'UiAutomator2',
  'appium:deviceName': 'Android',
  'appium:appPackage': 'com.android.settings',
  'appium:appActivity': '.Settings',
};

const wdOpts = {
  hostname: process.env.APPIUM_HOST || 'localhost',
  port: parseInt(process.env.APPIUM_PORT, 10) || 4723,
  logLevel: 'info',
  capabilities,
};

async function runTest() {
  const driver = await remote(wdOpts);
  try {
    const batteryItem = await driver.$('//*[@text="Battery"]');
    await batteryItem.click();
  } finally {
    await driver.pause(1000);
    await driver.deleteSession();
  }
}

runTest().catch(console.error);

Note

It's not within the scope of this guide to give a complete run-down on the WebdriverIO client library or everything that's happening here, so we'll leave the code itself unexplained in detail for now. You may want to read up particularly on Appium Capabilities in addition to familiarizing yourself with the excellent WebdriverIO documentation for a fuller explanation of the various API commands you see and what their purpose is.

Note

The sample code is available from GitHub Appium repository.

Basically, this code is doing the following:

  1. Defining a set of "Capabilities" (parameters) to send to the Appium server so Appium knows what kind of thing you want to automate.
  2. Starting an Appium session on the built-in Android settings app.
  3. Finding the "Battery" list item and clicking it.
  4. Pausing for a moment purely for visual effect.
  5. Ending the Appium session.

That's it! Let's give it a try. Before you run the test, make sure that you have an Appium server running in another terminal session, otherwise you'll get an error about not being able to connect to one. Then, you can execute the script:

node test.js

If all goes well, you'll see the Settings app open up and navigate to the "Battery" view before the app closes again.

Congratulations, you've started your Appium journey! Read on for some next steps to explore.