You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Overview

In this tutorial, we will create a test in Javascript+Mocha in order to validate a simple application interaction using Sauce Labs for cloud mobile testing.


Please note

Within this tutorial, only one Test Execution will be used; it will contain one Test Run with all the results for the different used browsers. Thus, the overall test run status will be affected by the results made for all the browsers.

Instead of this approach, a different one could be creating a Test Execution per each browser; this would require some adaptions in order to produce a XML report per each used browser. This approach would give the ability to take advantage of Test Environments (more info in Working with Test Environments).


Requirements

  • Install NodeJS
  • Install all dependencies using "npm"

Description

This tutorial is based on some examples from this project.

You may start by cloning the project's repository.

 git clone https://github.com/dwyl/learn-nightwatch


Nightwatch.js configuration is managed in a configuration file, similar to the following one.

nightwatch.conf.js
require('env2')('.env'); // optionally store your environment variables in .env
const seleniumServer = require("selenium-server");
const chromedriver = require("chromedriver");
const PKG = require('./package.json'); // so we can get the version of the project
const SCREENSHOT_PATH = "./node_modules/nightwatch/screenshots/" + PKG.version + "/";

const config = { // we use a nightwatch.conf.js file so we can include comments and helper functions
  "src_folders": [
    "test/e2e"     // we use '/test' as the name of our test directory by default. So 'test/e2e' for 'e2e'.
  ],
  "output_folder": "./node_modules/nightwatch/reports", // reports (test outcome) output by Nightwatch
  "selenium": {
    "start_process": true,
    "server_path": seleniumServer.path,
    "log_path": "",
    "host": "127.0.0.1",
    "port": 4444,
    "cli_args": {
      "webdriver.chrome.driver" : chromedriver.path
    }
  },
  "test_workers" : {"enabled" : true, "workers" : "auto"}, // perform tests in parallel where possible
  "test_settings": {
    "default": {
      "launch_url": "http://localhost", // we're testing a Public or "staging" site on Saucelabs
      "selenium_port": 80,
      "selenium_host": "ondemand.saucelabs.com",
      "silent": true,
      "screenshots": {
        "enabled": true, // save screenshots to this directory (excluded by .gitignore)
        "path": SCREENSHOT_PATH
      },
      "username" : "${SAUCE_USERNAME}",     // if you want to use Saucelabs remember to
      "access_key" : "${SAUCE_ACCESS_KEY}", // export your environment variables (see readme)
      "globals": {
        "waitForConditionTimeout": 10000    // wait for content on the page before continuing
      }
    },
    "local": {
      "launch_url": "http://localhost",
      "selenium_port": 4444,
      "selenium_host": "127.0.0.1",
      "silent": true,
      "screenshots": {
        "enabled": true, // save screenshots taken here
        "path": SCREENSHOT_PATH
      }, // this allows us to control the
      "globals": {
        "waitForConditionTimeout": 15000 // on localhost sometimes internet is slow so wait...
      },
      "desiredCapabilities": {
        "browserName": "chrome",
        "chromeOptions": {
          "args": [
            `Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46
            (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3`,
            "--window-size=640,1136" // iphone 5
          ]
        },
        "javascriptEnabled": true,
        "acceptSslCerts": true
      }
    },
    "chrome": { // your local Chrome browser (chromedriver)
      "desiredCapabilities": {
        "browserName": "chrome",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      }
    },
    "chromemac": { // browsers used on saucelabs:
      "desiredCapabilities": {
        "browserName": "chrome",
        "platform": "OS X 10.11",
        "version": "47"
      }
    },
    "ie11": {
      "desiredCapabilities": {
        "browserName": "internet explorer",
        "platform": "Windows 10",
        "version": "11.0"
      }
    },
    "firefox" : {
      "desiredCapabilities": {
        "platform": "XP",
        "browserName": "firefox",
        "version": "33"
      }
    },
    "internet_explorer_10" : {
      "desiredCapabilities": {
        "platform": "Windows 7",
        "browserName": "internet explorer",
        "version": "10"
      }
    },
    "android_s4_emulator": {
      "desiredCapabilities": {
        "browserName": "android",
        "deviceOrientation": "portrait",
        "deviceName": "Samsung Galaxy S4 Emulator",
        "version": "4.4"
      }
    },
    "iphone_6_simulator": {
      "desiredCapabilities": {
        "browserName": "iPhone",
        "deviceOrientation": "portrait",
        "deviceName": "iPhone 6",
        "platform": "OSX 10.10",
        "version": "8.4"
      }
    }
  }
}
module.exports = config;

function padLeft (count) { // theregister.co.uk/2016/03/23/npm_left_pad_chaos/
  return count < 10 ? '0' + count : count.toString();
}

var FILECOUNT = 0; // "global" screenshot file count
/**
 * The default is to save screenshots to the root of your project even though
 * there is a screenshots path in the config object above! ... so we need a
 * function that returns the correct path for storing our screenshots.
 * While we're at it, we are adding some meta-data to the filename, specifically
 * the Platform/Browser where the test was run and the test (file) name.
 */
function imgpath (browser) {
  var a = browser.options.desiredCapabilities;
  var meta = [a.platform];
  meta.push(a.browserName ? a.browserName : 'any');
  meta.push(a.version ? a.version : 'any');
  meta.push(a.name); // this is the test filename so always exists.
  var metadata = meta.join('~').toLowerCase().replace(/ /g, '');
  return SCREENSHOT_PATH + metadata + '_' + padLeft(FILECOUNT++) + '_';
}

module.exports.imgpath = imgpath;
module.exports.SCREENSHOT_PATH = SCREENSHOT_PATH;


The capabilities (devices/browsers) we want, along with the reporter/JUnit related configurations, are all defined in the previous configuraiton file.

Nightwatch.js provides a built-in JUnit reporter, which we'll use.




The test use the Page Objects pattern, implemented in several classes such as the following one.

pages/home.page.js
/**
 * Created by titusfortner on 11/23/16.
 */

var Page = require('./page');

var HomePage = Object.create(Page, {

    graphicsTab: {
        get: function () {
            return browser.element(`~Graphics`);
        }
    },

    click: {
        value: function (tabName) {
            if (tabName === "Graphics") {
                this.graphicsTab.click();
            } else {
                throwError("Not implemented");
            }
        }
    }

});


module.exports = HomePage;


Test: Verify the existence of a meny entry

tests/menu-test.js
var expect = require('chai').expect;

var HomePage = require('../pages/home.page'),
    MenuPage = require('../pages/menu.page');

describe('Mocha Spec Sync example', function() {
    it("verify Arcs entry in menu", function() {
        HomePage.click("Graphics");
        expect(MenuPage.arcsEntry.isVisible()).to.equal(true);
    });
});


Running tests locally


Test(s) then can be run using NPM "test" task.

npm test


After successfully running the tests and generating the JUnit XML reports (e.g. androidemulator.android.5_1.apidemos-debug_apk?raw=true.xmlsamsunggalaxys4emulator.android.4_4.apidemos-debug_apk?raw=true.xml), it can be imported to Xray (either by the REST API or through the Import Execution Results action within the Test Execution).

We'll use some shell-script sugar to do that for us and at the same time populate the Test Environment field on the Test Execution issues that will be created.

PROJECT=CALC
JIRASERVER=https://yourjiraserver
USERNAME=user
PASSWORD=pass
FIXVERSION=v3.0

for FILE in `ls *.xml`; do
 TESTENV=$(echo $FILE | cut -d "." -f 1-3)
 curl -H "Content-Type: multipart/form-data" -u $USERNAME:$PASSWORD -F "file=@$FILE"  "$JIRASERVER/rest/raven/1.0/import/execution/junit?projectKey=$PROJECT&testEnvironments=$TESTENV&fixVersion=$FIXVERSION"
done


In our case, two Test Executions will be created: one per each mobile device. Each one contains the same Test case.

   


   


Mocha tests are mapped to Generic Tests in Jira, and the Generic Test Definition field contains the namespace, the name of the class, and the method name that implements the Test case.

The execution screen details will provide information on the overall test run result.


Running in the cloud using SauceLabs

Before running the test(s), you need to export some environment variables with your Sauce Lab's username along with the respective access key, which you can obtain from within the User Settings section in your Sauce Lab's profile page.

export SAUCE_USERNAME=<your Sauce Labs username>
export SAUCE_ACCESS_KEY=<your Sauce Labs access key>


Test(s) then can be run in parallel using NPM.

npm run sauce


Multiple JUnit XML files will be created, one per capability (device+browser), under the node_modules/nightwatch/reports/ folder.


Please note

By using the junit-merge utility we can merge multiple JUnit XML reports and upload the merged report to Xray, although we'll loose the visibility of results on a per Test Environment basis.

If we want to have visibility of the results per Test Environment, then we need to separately upload them and identify the Test Environment on each REST API request.


In Sauce Labs you can see some info about it.

References

  • No labels