In the previous blog we set Appium to run with Jest and added desired capabilities to beforeAll hook. While this approach will work for a small project when you dealing with a fairly large application you would want to abstract it out. There are different ways of doing it, today we going to try one of it.

First lets look at our test file:

const wdio = require("webdriverio");
 
describe('Appium with Jest automation testing', () => {
let client
let field
beforeAll(async function(){
  opts = {
    path: '/wd/hub',
    port: 4723,
    capabilities: {
      platformName: "Android",
      platformVersion: "9",
      deviceName: "Android Emulator",
      app: "/path_to_the_file/ApiDemos-debug.apk",
      appPackage: "io.appium.android.apis",
      appActivity: ".view.TextFields",
      automationName: "UiAutomator2"
    }
  }
 
    client = await wdio.remote(opts);
    field = await client.$("android.widget.EditText");
 
})
 
afterAll(async function(){
    await client.deleteSession();
)}
 
   
test('First test', async function() {
    await field.setValue("Hello World!");
    const value = await field.getText();
    assert.equal(value,"Hello World!");
    })
  })
})

What we want to do is abstract out opts, lets add a new JSON file to root directory and name it android-caps.json

{
    "path": "/wd/hub",
    "port": 4723,
    "capabilities": {
      "platformName": "Android",
      "platformVersion": "9",
      "deviceName": "Android Emulator",
      "app": "/path_to_the_file/ApiDemos-debug.apk",
      "appPackage": "io.appium.android.apis",
      "appActivity": ".view.TextFields",
      "automationName": "UiAutomator2"
    }
  }

Now we will need to pass this JSON file to our opts, first let’s add it to package.json (from the previous post):

{
  "name": "appium-jest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "capabilities=android-caps.json jest --config=jest.config.js --detectOpenHandles --forceExit",
     
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "appium": "^1.17.1",
    "jest": "^26.0.1",
    "webdriverio": "^6.1.16"
  }
}

Now we can use node environment variables and pass the JSON using capabilities variable. Let’s go back to our test file and make changes.

const wdio = require("webdriverio");
const path = require("path");
 
describe('Appium with Jest automation testing', () => {
let client
let field
beforeAll(async function(){

  caps = path.resolve(process.env.capabilities) // get absolute path to json file
  opts = require(caps); // passing absracted json
 
    client = await wdio.remote(opts);
    field = await client.$("android.widget.EditText");
 
})
 
afterAll(async function(){
    await client.deleteSession();
)}
 
   
test('First test', async function() {
    await field.setValue("Hello World!");
    const value = await field.getText();
    assert.equal(value,"Hello World!");
    })
  })
})