Frequently asked questions

Where to find browser test examples

You can use the Synthetic-browser-script local runner to test and debug your script locally.

To create browser tests, see the Instana Synthetic Browser Script examples.

For more examples, see the following references:

Why a Selenium recorded script may not run successfully on Instana

Selenium recorded tests might fail on Instana if cookies and history exist in your web browsers, the pop-up windows such as "accept cookies" might not be visible in your websites. To avoid this issue, use Instana Synthetic-browser-script local runner to test your script locally after you create a test script.

With Instana Synthetic-browser-script, you can perform the following tasks:

  • Clear user profiles automatically: Even though you can successfully run your scripts locally with the Selenium IDE plug-in, the scripts might fail on Instana because of pop-up windows. You need to close the pop-up window before you perform an action. By using Synthetic-browser-script local runner, user profiles are automatically cleared. You need not manually clear cookies from your browser.
  • Test Instana extended browser testing APIs: If you want to use Instana extended browser testing APIs, you can use the Synthetic-browser-script local runner to test it. The runtime of the Synthetic-browser-script local runner is the same as the Instana Synthetic browser engine.

Selenium IDE is an open-source recording tool for generating locators such as CSS selectors, XPath, ID, and so on. Selenium IDE helps to identify web elements. However, it has the following limitations:

Test your script locally with Synthetic-browser-script local runner, which is provided by Instana. With this tool, you can see that the full browser UI prompts and perform your actions in the test scripts to help you debug and troubleshoot. If you have complex testing logic, such as loops, you can also try to use Instana Synthetic browser script tests, which is JavaScript-based. How to add manual steps to support Shadow DOM and so on, see other sections in this topic.

How to resolve the element is not clickable error

The test might fail with one of the following error messages:

  • is not clickable at point (285,436) because another element <li> obscures it
  • Failed to execute command clickElement {} element not interactable.

To resolve this issue, move your mouse to focus on the element. You can use one of the following methods.

Scroll to view and click

To scroll to view and click, use the following JavaScript command:

let element = await $browser.waitForAndFindElement(By.xpath(`//a[contains(.,'Customer stories')]`), 30000); 
await $browser.executeScript(`arguments[0].scrollIntoView()`, element); 
await $browser.executeScript(`arguments[0].click()`, element);									

For Selenium IDE recorded script, you can use runScript or executeScript to call Instana extended APIs to use the same JavaScript code:

{
"id": "b345d354-1d95-45d0-81ab-7c78695ed040",
"comment": "",
"command": "runScript",
"target": "let element = await $browser.waitForAndFindElement(By.xpath(`//a[contains(.,'Customer stories')]`), 30000); await $browser.executeScript(`arguments[0].scrollIntoView()`, element); await $browser.executeScript(`arguments[0].click()`, element)",
"targets": [],
"value": ""
}, 

For Selenium IDE script, use local runner to play back or test Instana advanced APIs. For example, $browser.waitForAndFindElement because Selenium IDE cannot recognize them. If you still want to play back or test your scripts with Selenium IDE, you can try the JavaScript code in the following example. The runScript command uses document.querySelector, which can be recognized by browsers. For a sample script, see how to scroll down and click next page in Google searched results.

{
"id": "d13e50bd-f698-4a04-9420-701a21dcde8d",
"comment": "",
"command": "waitForElementPresent",
"target": "css=#pnnext > span:nth-child(2)",
"targets": [],
"value": "20000"
},
{
"id": "b345d354-1d95-45d0-81ab-7c78695ed040",
"comment": "",
"command": "runScript",
"target": "const el = document.querySelector('#pnnext > span:nth-child(2)'); el.scrollIntoView(); el.click();",
"targets": [],
"value": ""
}

ActionChains

To move to the element and click, use ActionChains:

let element = await $browser.waitForAndFindElement($driver.By.linkText(`Business to business (BtoB) activities`), 10000); 
await $browser.actions().move({origin: element}).click().perform();

MouseOver in Selenium IDE script

For more information on mouseover in the Selenium IDE script, see MouseOver command.

To use MouseOver in a Selenium IDE script:

{
"id": "2d5c6b52-d2d7-4592-8052-87572a09e58b",
"comment": "",
"command": "mouseOver",
"target": "xpath=//dds-megamenu-category-link[contains(.,'Bridge observability and automated resource management')]",
"targets": [],
"value": ""
}, 

MouseOver is parsed as shown in the following code:

await driver.wait(until.elementLocated(By.xpath(`//dds-megamenu-category-link[contains(.,\'Bridge observability and automated resource management\')]`)), configuration.timeout);
await driver.findElement(By.xpath(`//dds-megamenu-category-link[contains(.,\'Bridge observability and automated resource management\')]`))
.then(element => {
    return driver.actions({
      bridge: true
    }).move({
      origin: element
    }).perform();
  });

Reasonable window size

The size of the window might be unusual when you record scripts with Selenium IDE. It might cause the error element not interactable or not clickable at point when you run tests on Instana.

To resolve this issue, try one of the following steps:

  • Remove the setWindowSize command. Instana will adjust the window size. Your script can still run successfully on Selenium IDE.
  • Set the maximum window size by using the JavaScript code. Use local runner to test it as shown in the following example:
{
"id": "4f719a79-aa76-4dc8-a18b-7b46523ae0e6",
"comment": "",
"command": "executeScript",
"target": "await $browser.manage().window().maximize();",
"targets": [],
"value": ""
},  

How to resolve StaleElementReferenceError

You might encounter the error StaleElementReferenceError: stale element reference: element is not attached to the page document. It is a common Selenium error.

This error occurs when your test script references a web element that is no longer attached to the DOM, which can occur with web pages that use frameworks such as React or Vue. To troubleshoot this issue, see the examples.

Testing whether your locators can identify unique web elements

This issue might arise because your locator returns multiple web elements, and it cannot identify unique elements. A locator can be CSS selectors, XPath, ID, and so on. It is the expression in the Target property in Selenium IDE.
In the following example, the CSS locator a[href*='/#/home'] span returns multiple web elements, which might cause the test to fail because of stale element reference. To test your locators, enter it in the browser, go to More tools > Web Developer tools. A good locator can highlight the unique web element. You can update or change your locators if you see multiple matching results as shown in the following example. test-locators

To select different locators with Selenium IDE, click the Target property. Consider choosing one meaningful locator irrespective of the position of the web element. A good locator can identify the unique web elements irrespective of the window size or UI position adjustment. selenium-locators

Locating the element again after it is attached to the DOM

You can discard the current reference you hold and replace it, possibly by locating the element again after it is attached to the DOM.

Other than item 1, the web element can be stale for any of the following reasons:

  • A page refresh
  • DOM update
  • Location of the web element is changed

The StaleElementReferenceError can occur because of the following reasons:

  • The selected web element to interact with is no longer present on the HTML web page.
  • The selected web element was destroyed completely and recreated.

Example code with StaleElementReferenceError:

// retrieving an input HTML element from the page
let nameHtmlElement = await $browser.findElement(nameInputBy);
// setting a name in the input element
await nameHtmlElement.sendKeys("John");

// refreshing the page
await $browser.navigate().refresh()

// nameHtmlElement is now stale
// trying to set a new name, but this will throw a StaleElementReferenceException
await nameHtmlElement.sendKeys("Maria");

To fix this issue, try to find the element again before you use it.

// refreshing the page
await $browser.navigate().refresh()
nameHtmlElement = await $browser.findElement(nameInputBy);
await nameHtmlElement.sendKeys("Maria");

Some users use try-catch-retry solutions. You can use Retry Strategy on Instana. If you set Retry Strategy as Retry twice, when the test fails the test is retried up to 2 times. Or you can search for StaleElementReferenceError to find more solutions in the browser testing field to address it in your test script code.

Waiting for the page refreshed

If the issue is still not resolved, try to use the pause command or await $browser.sleep to wait a few seconds until the page or iframe is refreshed. Before you locate elements and use them, wait for the page to be “static” to avoid the stale element reference issue. Adding some pause time and using Instana Retry strategy might prevent such issues. To use Instana Retry strategy, you can set the number of retry attempts on the Instana test configuration page, set it to 1 or 2. Then, your test is run at most three times until it is successful before the result is sent to the Instana backend.

// wait 5 seconds OR wait until tab is visible
// click the tab
// wait 5 seconds OR wait until button is visible
// Click button
await $browser.sleep(5000);
{
"id": "75135e0f-5f38-4004-b0f2-fda657d73bb3",
"comment": "",
"command": "pause",
"target": "2000",
"targets": [],
"value": ""
},

Searching for keywords in GitHub is shown in the script example.

To resolve the "stale element reference" error, use the pause and waitForElementPresent commands:

  • Add the pause command to wait for the page to refresh before the tabs are switched.
  • Add the waitForEelementPresent command to wait for the suggestion list to appear before you enter characters in the field.

selenium-solution selenium-solution

How to verify test results

How to verify whether your test case is successful?

In the browser testing field, use Assertions, Explicit WAIT to verify your test results. Thus, you can ensure your web page is loaded and rendered as expected. With Instana browser testing, you can also generate screenshot for your test run and check console logs (Echo command in Selenium recorded scripts), browser logs, and timeline chart.

The following commands can be helpful:

{
      "id": "938df959-9b65-4ae4-a2f5-59be6188ea5f",
      "comment": "This is how to sleep for 5 seconds.",
      "command": "pause",
      "target": "5000",
      "targets": [],
      "value": ""
},
{
    "id": "2d5c6b52-d2d7-4592-8052-87572a09e58b",
     "comment": "This is how to take screenshot",
     "command": "executeScript",
     "target": "await $browser.takeScreenshot()",
     "targets": [],
     "value": ""
}

You can also try the following Assertion commands:

{
    "id": "46eb59c2-5fd6-4481-b3e8-eaaddab79a69",
    "comment": "This is one type of Assertions in browser testing",
    "command": "assertTitle",
    "target": "instana - Google Search",
    "targets": [],
    "value": ""
}

How to use Explicit Wait to verify your test in browser script test is shown in the following example:

await $browser.waitForAndFindElement($driver.By.xpath(`//h1[contains(text(), 'Websites & mobile apps')]`), 30000)
await $browser.wait($driver.until.titleContains(`Websites – Websites & mobile apps`), 30000);

Try adding the following commands in your recorded side file:

{
      "id": "615cb3e5-fe2a-4859-b0aa-9df52f22028f",
      "comment": "This is Explicit Wait in browser testing",
      "command": "waitForElementPresent",
      "target": "id=mainmenu",
      "targets": [],
      "value": "30000"
},
{
      "id": "03e23d25-38e3-4051-81ff-740109350ee8",
      "comment": "This is how to add logging message in console logs",
      "command": "echo",
      "target": "Verify UI dashboard",
      "targets": [],
      "value": ""
}

How to switch to frame or iframe

If your website uses frames, you might encounter the no such element error.

To resolve this issue, switch to the frame or iframe with $browser.switchTo().frame(id: number | WebElement);.

To switch to the frame or iframe for the Instana Browser script test:

let frameElement = await $browser.waitForAndFindElement($driver.By.xpath('//*[contains(@id, "pop-frame")]'), 10000);
await $browser.switchTo().frame(frameElement);

How to find web elements

To find web elements, see the reference from Selenium on locator strategies.

Function Description
$browser.waitForAndFindElement($driver.By.id("boxyear"), 1000) Wait and find element by ID until the element is visible or the timeout value is reached
$browser.findElements($driver.By.css('select')) Search for multiple elements on the page with the CSS selector
$browser.findElement($driver.By.linkText("About")) Find element by linkText
$browser.findElement($driver.By.xpath('//input[@value='f']')) Find element by XPath

The format of the CSS selector is By.css(element[attribute='attribute-value']).

The format of XPath expression is By.xpath("//element[@attribute='value']") or By.xpath("//*[@attribute='value']").

To find an element by attributes, for example <a href="mysite.com"></a>, run:

// CSS selector
$driver.By.css(a[href*="example"] )
// XPath expression
$driver.By.xpath("//a[contains(@href,'Electronics')]")
$driver.By.xpath(`//dds-footer-nav-item[contains(.,'Developer education')]`)

To change from the default locator on the Selenium IDE plug-in, click the target.

Selenium-locators

How to select an element from the drop-down list

You can select an element from a drop-down list by using the select command. With the Value property, you can select a value from a series of options with label=, value=, id=, or index=. If no prefix is provided, a match on the label is used. Use label, value, or id instead of index. Otherwise, the results between Instana and Selenium IDE might not be compatible.

How to select June in the drop-down list with the select command is shown in the following example. The methods to select the June option are shown in line numbers 3, 4, and 5. These methods work on Selenium IDE and Instana.

<select id="month" name="month" class="inline six" onchange="document.cf.typ[1].checked=true">
  <option value="1">January</option>
  <option value="2">February</option>
  <option value="3">March</option>
  <option value="4">April</option>
  <option value="5">May</option>
  <option value="6">June</option>
  <option value="7">July</option>
  <option value="8" selected="">August</option>
  <option value="9">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select>

Selenium-select

How to resolve the no such element error

Explicit wait is a well-known Selenium best practice to avoid the no such element errors and reduce waiting or sleeping time. Explicit wait is preferred in comparison with Implicit wait and $browser.sleep.

To use Explicit wait on the Instana, run the commands as shown in the following examples:

// wait until the title comes out
await $browser.wait($driver.until.titleContains('Year 2023 Calendar'), 10000);

// Call the wait function.
await $browser.wait(function () {
    return $browser.getTitle().then(function (title) {
      return title.includes("Google");
    });
  }, 10000);

await $browser.wait(async function () {
    const title = await $browser.getTitle();
    return title.includes("Google");
  }, 10000);

// waitForAndFindElement API
const cookies = await $browser.waitForAndFindElement(
    $driver.By.id(`truste-consent-button`),
    30000
);
await cookies.click();

In the Selenium IDE script, you can use WAIT command as shown in the following example. Enter the waiting time in milliseconds for the value property.

{
"id": "d13e50bd-f698-4a04-9420-701a21dcde8d",
"comment": "",
"command": "waitForElementPresent",
"target": "id=result-stats",
"targets": [
    ["id=result-stats", "id"],
    ["css=#result-stats", "css:finder"],
    ["xpath=//div[@id='result-stats']", "xpath:attributes"],
    ["xpath=//div[@id='slim_appbar']/div/div", "xpath:idRelative"],
    ["xpath=//div[7]/div/div/div/div/div", "xpath:position"]
],
"value": "10000"
}

How to capture a screenshot with the Selenium IDE script

To call Instana extended APIs, run the runScript or executeScript command with the Selenium IDE scripts.

{
"id": "e781c454-0080-447a-b905-7183443956f3",
"comment": "",
"command": "runScript",
"target": "await $browser.takeScreenshot()",
"targets": [],
"value": ""
}

How to handle drop-down lists in Synthetic browser test

Items in the drop-down list are selected with findElement and click.

<select id="month" name="month" >
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
...
</select>

// find element by css or xpath
await $browser.findElement($driver.By.css(`#month > option:nth-child(3)`)).click(); 
await $browser.findElement($driver.By.xpath(`//select[@id='month']/option[3]`)).click();

// wait until element located and do assertion
await $browser.wait($driver.until.elementLocated($driver.By.id("month")), 3000).click();
assert.equal(5, await $browser.findElement($driver.By.id("month")).getAttribute("value"));
await $browser.findElement($driver.By.xpath("//select[@id='month']/option[3]")).click();
assert.equal(3, await $browser.findElement($driver.By.id("month")).getAttribute("value"));

How to handle Shadow DOM elements

To test the shadow DOM elements, use the getShadowRoot() function.

The getShadowRoot() function is supported on Instana Synthetic PoP Helm chart 1.1.1 or later. You must upgrade your Synthetic PoP to 1.1.1 or later to use Shadow DOM interaction.

To use the getShadowRoot() function, run the following command:

let shadowHost = await $browser.waitForAndFindElement(shadowHostSelector, timeout); 
let shadowRoot = await shadowHost.getShadowRoot();
let element = await shadowRoot.findElement(elementSelector);
console.log("element text is:", await element.getText(), ", id is:", await element.getId());

Or use Instana Advanced APIs in Selenium IDE recorded scripts and use local runner to test it:

{
"id": "4f602785-2a19-4b5f-a23c-7ae6f6e58d5d",
"comment": "",
"command": "executeScript",
"target": "let shadowHost = await $browser.waitForAndFindElement($driver.By.css(`.field > q2-input`), 10000); let shadowRoot = await shadowHost.getShadowRoot(); let element = await shadowRoot.findElement($driver.By.css(`*[type='text']`)); await element.sendKeys(`user1`); ",
"targets": [],
"value": ""
}, 

How to verify text on the page with partial matching

To verify text on your page with partial matching, you can use findElement by XPath.

Verifying page contents on the Browser script test

To verify page contents on the Browser script test:

let element = await $browser.findElement(By.xpath(`//h1[contains(text(), 'Action Result')]`));
console.log("Found element:", await element.getTagName(), ", element text is:", await element.getText());

await $browser.waitForAndFindElement(By.xpath(`//label[contains(text(), 'Action Result')]`), 5000);
console.log(">>>>>>>>>>>>>>>>>>>", "Action Result found");

Verifying page contents on the Selenium IDE recorded script test

To verify page contents on the Selenium IDE recorded script test:

{
"id": "4cbe70ec-48b2-4e57-97cf-6d855fa0f08f",
"comment": "",
"command": "waitForElementVisible",
"target": "//h1[contains(text(), \"Selenium automates\")]",
"targets": [],
"value": "30000"
}

Selenium-command

How to log on to websites with two-factor authentication

For BrowserScript and Selenium SIDE script tests, 2FA (two-factor authentication) is supported to log on to websites.

For the complete test script, see BrowserScript example and Selenium SIDE example.

To test the script or run the script locally, replace the url and $secure variables in the synb.json file with the actual values.

To pass 2FA, complete the following steps:

  1. Get the Time-based One-Time Password (TOTP) secret key, a randomly generated, shared secret between you and the website to create the TOTP token for signing in to the website with two-factor authentication (2FA). This secret key is typically provided to you in the form of a QR code or a digital code during the initial setup of 2FA. To get the digital code, click on any of the following help links on the two-factor authentication configuration page:
    • Can’t scan the QR code
    • Problem scanning? Enter a code instead.
  2. To protect your secret key, create Synthetic credentials for TOTP secret key by using the Instana Open API.
  3. In your browser test, use the $browser.generateTOTPToken(key: string) browser testing API to create a time-based TOTP token for inputs.
    • To use BrowserScript for 2FA authentication:
      let totp_token = $browser.generateTOTPToken($secure.totpKey);
      await findElementByIdAndSendKeys("password", totp_token);
      
    • To use Selenium SIDE script for 2FA authentication:
      {
         "id": "ec51296b-4d16-4167-ac83-ba87f89cc0c7",
         "comment": "Generate a TOTP token from a TOTP key",
         "command": "executeScript",
         "target": "return $browser.generateTOTPToken($secure.totpKey);",
         "targets": [],
         "value": "totpToken"
      }, {
         "id": "3cbc306a-ed33-46bf-9923-92752b0466f2",
         "comment": "",
         "command": "type",
         "target": "id=password",
         "targets": [],
         "value": "${totpToken}"
      },