The error message "window is not defined" occurs when the external file 'signalr.min.js' is included

Updates

  • OpenTest --version 1.2.2
  • ChromeDriver 85.0.4183.87

Whenever I attempt to add the necessary external javascript files, it results in the following errors:

Caused by: java.lang.RuntimeException: Failed to evaluate JavaScript code at line number 1. The script content was: 
$include(["signalr.min.js", "signalr.tests.js"]);
...
Caused by: java.lang.RuntimeException: Failed to run script file signalr.min.js
...
Caused by: javax.script.ScriptException: ReferenceError: "window" is not defined in <eval> at line number 1

I have consulted the documentation at:

Despite trying various combinations, none of them seem to be effective. It appears that I am overlooking something :(

My actor.yml file is set up with the chrome web-driver configured as follows:

# Selenium options
selenium:
    # seleniumServerUrl: http://127.0.0.1:9515
    desiredCapabilities:
        browserName: chrome
        chromeOptions:
            args: [ --start-maximized ]
    chromeDriverExePath: C:/Webdrivers/chromedriver.exe
    chromeDriverExeArgs: [--start-maximized, --ignore-certificate-errors, --disable-popup-blocking, --disable-extensions-file-access-check, "--test-name", "--disable-extensions", "--disable-notifications", "--disable-web-security", "--disable-prompt-on-repost", "--browser-test", "--dom-automation", "--enable-caret-browsing", "--expose-internals-for-testing", "--force-login-manager-in-tests" ]

An illustration of the problematic test:

description: My Test
actors:
  - actor: ACTOR1
    segments:
      - segment: 1
        actions:
          - description: include external SignalR script files
            script: |
                $include(["signalr.min.js", "signalr.tests.js"]);

          - description: Initialize SignalR Connection
            action: org.getopentest.selenium.ExecuteScript
            args:
              scriptArgs: $data("config").webChatUrl + $data("config").apiV1SignalRChathub
              script: |
                var hubUrl = arguments[0];
                SignalRConnectionTest(hubUrl);

You can access the signalr.min.js file at: https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.7/signalr.min.js

Answer №1

After numerous trials and errors, I finally found a solution that works. I couldn't get the script-includes to work in OpenTest, probably because of issues when the browser is not yet opened and the window object is undefined. This means scripts that rely on the DOM won't work...

What I ended up doing was creating a local HTML page that executes some JavaScript, and then calling that page from the OpenTest YAML file with some validations. Here is an example of how I approached this:

description: My Test
actors:
  - actor: ACTOR1
    segments:
      - segment: 1
        actions:
          - description: Initialize Browser
            action: org.getopentest.selenium.NavigateTo
            args:
              url: $data("config").someExternalUrlIsAlive
              
          - description: Get Test Page File-Path
            script: |
              var File = Java.type("java.io.File");
              var URLEncoder = Java.type("java.net.URLEncoder");
              var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");

              var testPage = new File("..\\test-repo\\scripts\\testpage.html");
              var testPageUrl = testPage.getAbsolutePath();

              var argument = $data("config").someProperty;
              var argumentUrlEncoded = URLEncoder.encode(argument, StandardCharsets.UTF_8.toString());

              $sharedData.testpage = testPageUrl + "?arg=" + argumentUrlEncoded;
              $log("The test-page path is " + $sharedData.testpage);

          - description: Navigate to Test Page
            action: org.getopentest.selenium.NavigateTo
            args:
              url: $sharedData.testpage

          - description: Start Test
            action: org.getopentest.selenium.Click
            args:
              locator: { id: btnTest }

          - description: Give the test some time to complete
            script: |
              var Thread = Java.type("java.lang.Thread");
              Thread.sleep(3000); // sleep 3 seconds.

          - description: Read Test Page Result
            action: org.getopentest.selenium.GetElements
            args:
              locator: { id: txtResult }
              $localData:
                resultElements: $output.elements

          - description: Validate the Test Page Results
            script: |
              var txtResult = $localData.resultElements[0];
              var testResult = txtResult.getAttribute("value")

              if (testResult !== "200") {
                $fail(
                  $format(
                    "We expected a valid connection result, but we got: {0}",
                    testResult
                  )
                );
              }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the implementation of JavaScript bit-shift and bit-wise operations in Java

I'm currently attempting to emulate the functionality of JavaScript bit-shift and bitwise operations in Java. Have you ever tried to accomplish this task, and how can it be done reliably and consistently even when dealing with long integers? var i ...

expired: the item has either become detached from the webpage or the site has been reloaded

I am facing an issue while trying to log in using Selenium Webdriver (Java) on the website: www.tokopedia.com. I managed to input my email and password, but upon clicking the login button, it returns an error. I wonder why this is happening and what could ...

upright scrolling mouse slider

In my project, I have implemented a vertical slider with mousewheel control using SwiperJS from https://swiperjs.com/. Although the slider is working perfectly fine, I am looking to fix the positions while scrolling on the page similar to the example pro ...

Trouble fetching data for my controller in AngularJS using UI Router resolve

My attempts to inject a resolve object containing loaded data into my controller are resulting in an Unknown Provider error : Error message: Unknown provider: configServiceProvider <- configService Below is the code I am working with: StateProvider ...

Uncover the content of an element with Selenium in Java

I need to extract the message "We didn't recognize that email and/or password." using Selenium with Java. <div class="styles_errorDisplayInnerContainer_3R2ni-zSvPIKWfKXiviJhH"> <span class="styles_questionMarkContainer_10mxHNOMojCyG6bxLH ...

Foreign keys in a one-to-many relationship with Sequelize.js

I am in the process of developing a survey application using Node.js/Express and MySQL incorporating Sequelize.js ORM. However, I am encountering difficulties while establishing the relationship between the two models. My goal is to have the Questions&apo ...

Attempting to alert a particular device using Flutter for notification delivery

Currently, I am developing a Chat app using Flutter and attempting to send notifications to specific devices through Firebase functions. Initially, I retrieve the device token and store it in Firebase. Now, my challenge lies in fetching the token and invok ...

Adjust website content depending on user's authentication status

My goal is to display a logout button when the user is logged in and a login button if they are not. I am using JSON tokens to determine if a user is logged in or not, by checking if the token is null. However, this approach does not seem to be working. Ca ...

Delete the initial instance of a specific element with JavaScript or Lodash

I am working with an array that looks like this - ["a", "a", "b", "c", "d", "e"] My goal is to filter this array in a way that removes only the first occurrence of each element. Based on the exa ...

PhantomJS Error Alert: Something went wrong in the system

Attempting to retrieve price data tables for different commodities on specific dates from Investing.com, using Selenium and PhantomJS in R. Below is my PhantomJS script that focuses on extracting silver prices. However, I keep encountering errors, especi ...

'The object of type '{}' does not support indexing with a 'string'

I am currently working on a React component that dynamically generates an HTML Table based on an array of objects. The columns to be displayed are specified through the property called tableColumns. While iterating through the items and trying to display ...

The CORS problem arises only in production when using NextJS/ReactJS with Vercel, where the request is being blocked due to the absence of the 'Access-Control-Allow-Origin' header

I've encountered a CORS error while trying to call an API endpoint from a function. Strangely, the error only occurs in production on Vercel; everything works fine on localhost. The CORS error message: Access to fetch at 'https://myurl.com/api/p ...

How can I update the color of table rows after the ng-repeat has been implemented?

My current project involves Django, Python, and a bit of AngularJS. I have a dynamic history table that grows as data is added. I am looking to apply some simple CSS to this table - specifically, I want to give every even-numbered row a black background ...

Using JQuery to make an AJAX request with URL Rest path parameters

Currently, I have a REST service located at /users/{userId}/orders/{orderId} and I am looking to make a call to it using JQuery. Instead of simply concatenating the IDs like this: $.get( 'users/' + 1234 + '/orders/' + 9876, fu ...

Browsers seem to only respond to the FileReader onload event on the second try

Currently I am working on implementing in-browser image processing using HTML5 and encountering a strange issue specifically in Chrome. The problem lies with the onload event handler for the File API FileReader class, as the file is only processed correctl ...

The Chrome browser stubbornly refuses to close even after the completion of the test

@BeforeMethod public void setup () { System.setProperty("webdriver.chrome.driver", "src\\test\\resources\\chromedriver.exe"); driver = new ChromeDriver(); // Opens Chrome browser driver.manage().timeouts().implici ...

Leveraging the callback function to display information from a JSON file

Attempting to retrieve JSON data from a PHP file and display it. Managed to successfully request the data via AJAX and log it to the console. (At least one part is working). Tried implementing a callback to ensure that the script waits for the data befor ...

Searching for the position of objects within a collection?

I am seeking the ability to parse through an object and allocate each of its available attributes to a variable. Within this scenario, there are four potential properties present in different objects - some containing all four while others may only have t ...

The quiet harmony of FeathersJS and Socket.io as they attentively listen to events is

I've been working hard to get everything set up and running smoothly, but it seems like I'm stuck on the last piece of the puzzle. Despite following the documentation closely, I can't seem to figure out what I'm missing. Here is the @an ...

Issue with callback function not triggering after comment deletion in REACT

Although I am successfully able to delete the comment, I am facing an issue where the callback function is not being invoked. My suspicion is that it might be related to how I pass multiple arguments to the function, but I cannot confirm this. Below is th ...