Nightwatch.js commands

Loadero uses Selenium Nightwatch and TestUI (Java) to handle participant action simulation. Nightwatch offers a lot of their own commands to handle interaction with browser.

Nightwatch built in command documentation can be found here.

In addition to built-in nightwatch commands, Loadero team is working on implementing additional custom commands to accomplish other tasks that would not be possible otherwise.

Available third party libraries

Additional libraries are installed and available in script:


Available script variables

Loadero offers some variables that can be accessed in script. These variables hold information relevant to the participant that is executing test. Variables are available through client.globals directive.

  • participant.id (int): ID of participant that is executing test. This ID is unique inside group
  • participant.name (string): name of participant as defined in participant configuration
  • group.id (int): ID of group in which participant is executing test. This ID is unique within test run
  • group.name (string): name of group as defined in group configuration
  • run.id (int): ID of this test run
  • test.name (string): name of current test
  • network (string): network conditions of this participant
  • browser (string): browser version used
  • mediaType (string): media type of simulated audio/video feed
  • location (string): region where current participant is located

Script examples

Locating elements by using CSS selectors

client.useCss();

This command sets element locator strategy to CSS. CSS is also the default strategy used by Nightwatch.

[!EXAMPLE]

function(client) {
    client
        // Navigates to website google.com
        .url('https://www.google.com')
        // Waits up to 10 seconds for page to load up (for body element 
        // to get visible)
        .waitForElementVisible('body', 10000)
        // Types "loadero" in search bar
        .setValue('input[type=text]', 'loadero')
        // Sends 'click' command to browser for search button element
        .click('input[value~="Google"][class="lsb"]');
}

Locating elements by using xPath selectors

client.useXpath();

Sets the locate strategy for selectors to xPath. It is possible to use both xPath and CSS strategies by switching back and forth.

[!EXAMPLE]

function(client) {
    client
        .useXpath()
        // Navigates to website google.com
        .url('https://www.google.com')
        // Waits up to 10 seconds for page to load up (for body element 
        // to get visible)
        .waitForElementVisible("//body", 10000)
        // Types "loadero" in search bar
        .setValue('//input[@type="text"]', 'charizard evolution chart')
        // Sends 'click' command to browser for search button element
        .click('//input[contains(@value, "Google") and @class="lsb"]');
}

Using Nightwatch assertions

Nightwatch native assertions are called by two methods, depending on expected result after error is asserted: .assert and .verify

Once this assertion fails, test is ended and any assertions further in the script are skipped:

client.assert.visible(".non-existing-element-class");

This assertion will log out the failure, and continue with the test:

client.verify.visible(".non-existing-element-class");

[!EXAMPLE]

function(client) {
    client
        .url('https://www.testdevlab.com')
        .waitForElementVisible('body', 10000)
        // Checks if the page url contains given value, if not then stops test
        .assert.urlEquals('https://www.testdevlab.com/')
        // Verifies if the page title contains given value, if not logs error
        .verify.title(
            'TestDevLab - Your partner in software quality assurance'
        )
        // Checks if the element is visible
        .assert.visible('a[href="/careers"]')
        .click('a[href="/careers"]')
        .takeScreenshot('Recruitment.png');
}


Custom commands

Perform command with custom timeout

client.performTimed(callback: function, timeout: int);

Provides the same functionality as built-in Nightwatch .perform() command, but allows to set custom done invocation timeout value in milliseconds.

Built-in .perform() command uses asyncHookTimeout value for the done invocation timeout. By default asyncHookTimeout value is set to 10 seconds, but there may be cases where this value should be customized in order to control callback maximum execution time. So to allow to define this value for each case separately and avoid asyncHookTimeout redefining .performTimed() command was created.

The callback parameter defines the function that will be executed as part of the command queue. Same as built-in .perform() command the callback signature can have up to two parameters:

  • no parameters - callback runs and perform completes immediately at the end of the execution of the callback.
  • one parameter - allows for asynchronous execution within the callback providing a done callback function for completion as the first argument.
  • two parameters - allows for asynchronous execution with the Nightwatch api object passed in as the first argument, followed by the done callback.

The timeout parameter specifies the time in milliseconds, that describes the done invocation timeout.

[!TIP] The .performTimed() command will be useful in cases where done callback is used within the custom callback function in order to notify the Nightwatch command queue about the end of command execution. Without the done callback invocation .performTimed() command behaves the same as built-in .perform() command and completes immediately after the callback is run.


[!EXAMPLE]

function (client) {
  function setTime (timestamp, done) {
      fetch("https://myendpoint.com/post", {
          method: "post",
          headers: {
              "Accept": "application/json",
              "Content-Type": "application/json"
          },
          body: JSON.stringify({ timestamp })
      })
      .then(() => done())
      .catch(error => done(error));
  };

  client
      .url('https://mypage.com/')
      .takeScreenshot('screenshot_before.png')
      .performTimed(function(done) {
          setTime(new Date().getTime(), done);
      }, 20000)
      .takeScreenshot('screenshot_after.png')
};


Take screenshot during test

client.takeScreenshot(filename: string, exitOnFail: bool);

Creates a browser screenshot and saves it for retrieval after test execution has finished.

[!NOTE]

Since these screenshots are uploaded only after selenium script has fully exited, screenshots could be lost if test was aborted early or has failed.

The filename parameter specifies name of the file when it will be saved.

The exitOnFail parameter lets participant terminate test execution if there was a problem taking screenshot. This parameter can be omitted and will default to false.

[!EXAMPLE]

function (browser) {
    browser
        .url('https://google.com')
        .waitForElementVisible('body', 10000)
        .takeScreenshot('screenshot.png');
}

[!WARNING]

Screenshot creation is impossible in some cases, for example, when an alert is open.


Set file into file input field

client.setFile(selector: string, fileName: string);

Allows to set one of Loadero sample files into file input field.

The selector parameter specifies input field element selector, e.g. input[type="file"], input#file-upload.

The fileName parameter specifies chosen file name.

Available test files

For now, one of predefined test files can be chosen. Available files:

File name (fileName) Type Size
loaderoSample100KB.png PNG 100KB
loaderoSample1MB.png PNG 1MB
loaderoSample5MB.png PNG 5MB
loaderoSample30MB.png PNG 30MB
loaderoSample100MB.txt TXT 100MB

In case there is a need for other file format or size, feel free to contact us.

[!EXAMPLE]

  function(browser) {
      browser
          .url("https://www.myawesomepage.com")
          .waitForElementVisible("body", 10000)
          .setFile("input#file-upload", "loaderoSample100KB.png")
          .pause(1000)
          .takeScreenshot("fileSet.png");
  }


Set User-Agent

client.setUserAgent(userAgent: string);

Changes User-Agent header for outgoing requests. To switch back to original user agent, call the function with empty value.

The userAgent parameter specifies prefered User-Agent header value.

[!EXAMPLE]

function(client) {
  client
    // Open page and create screenshot with default User-Agent
    .url('https://www.whatismybrowser.com/detect/what-is-my-user-agent')
    .waitForElementVisible('body', 1000)
    .takeScreenshot('UADefault.png')
    // Set custom User-Agent header
    .setUserAgent("custom")
    // Refresh page
    .refresh()
    // Wait for page to load and create screenshot with changed User-Agent
    .waitForElementVisible('body', 1000)
    .takeScreenshot('UACustom.png')
    // Reset User-Agent header to default value
    .setUserAgent("")
    // Refresh page
    .refresh()
    // Wait for page to load and create screenshot with changed User-Agent
    .waitForElementVisible('body', 1000)
    .takeScreenshot('UARevert.png');
}


Update network conditions during test

client.updateNetwork(networkMode: string);

Updates network conditions for the participant while the test is running.

The networkMode parameter specifies what network conditions should be used. Available network configurations and networkMode parameter values can be found here.

[!EXAMPLE]

function (browser) {
    browser
        .url('https://google.com')
        .waitForElementVisible('body', 10000)
        .updateNetwork('3g');
}

results matching ""

    No results matching ""