Angular Protractor: Leveraging Browser Context for Executing Scripts

Within my index.html file, I explicitly define the following:

window.myAppInstance = new MyApp.myAppConstructor();

In the todo-spec.js file, I set up the following structure:

describe('verifying my web page', function() {
  it('should confirm the existence of "myAppInstance" object on the window', function() {
    browser.get('https://my.web.page.com');

    function checkMyTest() {
      return Object.keys(window.myAppInstance).sort();
    };

    var p = browser.driver.executeScript(checkMyTest);
     p.then(function(result) {
        console.log("success");
        console.log(result);
     }, function() {
        console.log("error occurred");
        console.log(arguments);
     });
  });
});

However, when using Protractor, my application is not detected. It returns either null or undefined:

Error
{ '0':
   { [WebDriverError: unknown error: Cannot convert undefined or null to object
 (Session info: chrome=50.0.2661.102)
... and various other irrelevant information

Yet, when inspecting Chrome's console, I am able to execute

window.myAppInstance

without any issues, displaying the object correctly.

How can I retrieve this window object during my Protractor test?

Note 1: Clarification provided regarding the constructors.

Note 2: My application uses manual bootstrapping in AngularJS. Upon further examination, I include this line in my test:

<snip>
  browser.get('https://my.web.page.com');
  **browser.pause()**
<snip>

Current steps: 1) Press F12 to bring up Chrome developer tools 2) Check the console for errors indicating a crashed app 3) Manually refresh the browser 4) Observe the successful reload of the app. Confusion sets in as to why programmatically launching the page with

browser.get('https://my.web.page.com'); 

differs enough from manually entering the URL in the browser to cause issues.

I now ponder, What factor in running the tests via Protractor would lead to the failure of my app?

Answer №1

It's possible that there is a timing issue where the value being sought is not currently available. In this case, you may need to wait for it to become accessible:

function checkForKey() {
  return browser.executeScript("return window.myAppXXXXXXXXXXXXX");
}

browser.wait(checkForKey, 5000);
var result = browser.executeScript(myCode);
// ...

Answer №2

It is highly likely that your object myAppXXXXXXXXXXXXX has not been instantiated by the time the function myTest is being executed. In this scenario, one possible solution would be to utilize executeAsyncScript to retrieve the keys of the object once it becomes available:

function myCustomTest(callback){
  if (window.myAppXXXXXXXXXXXXX) {
    callback(Object.keys(window.myAppXXXXXXXXXXXXX).sort());
  } else {
    setTimeout(myCustomTest, 30);  // retry in 30 milliseconds
  }
}

browser.driver.executeAsyncScript(myCustomTest)
  .then(function(result) {
    console.log("Success!");
    console.log(result);
  }, function() {
    console.log("An error occurred.");
    console.log(arguments);
  });

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

Having trouble retrieving information from a website with Selenium

Hey there! I am a beginner in the world of data scraping using Selenium and I've encountered an issue while trying to extract information from this specific website. What I'm looking to gather are all the rows pertaining to these three columns: ...

Angular: URL is lost upon second click during state change

There are 4 different states, each representing a unique visualization. The first state displays a map, while the remaining three states show pie charts. By default, the map visualization is loaded. However, there are icons available to switch to the othe ...

Load jQuery to display the Bootstrap modal.ORUse jQuery to load and

My attempt to use the .load() function to display a bootstrap modal immediately on my page isn't working. The modal opens but cannot be closed afterward. The goal is to load a list of players in a modal whenever a team name with the class .team is cl ...

Even with a correct XPath and the element present, Webdriver inexplicably throws a NoSuchElementException

There are 20 Google review score elements on a page like this. https://i.sstatic.net/9ErFS.png The XPath for each element is: //ol/div[2]/div/div/div[2]/div[%s]/div/div[3]/div/a[1]/div/div/div[2]/div/span To extract the review counts using Python and W ...

Token authentication in subdomain with Web Api 2

Currently, I am developing a website with AngularJS and utilizing the WebApi2 token authentication template for Individual User Accounts. My goal is to have two sites logged in simultaneously, one at www.domain.com and the other at sub.domain.com For user ...

Changing color when mouse hovers using Jquery

Currently, I am in the process of converting a flash ad into an html5 ad. I found this demo here, and I would like to replicate the mouse hover effect showcased. When the cursor hovers over the details text in the banner, the entire background changes to ...

Adding ng-messages to a new input element that is generated dynamically in an AngularJS application using Material Design can be

I'm having an issue with my code. Everything is working fine except for the ng-messages part - they are not displaying as expected. I believe that ng-messages should be attached to the 'name' element, but it's not working in this case. ...

Struggling with Responsiveness: Challenges with Detailed Information and Image Grid Design

Encountering challenges in achieving the desired responsiveness for a grid layout consisting of details and an image. The layout displays correctly on desktop screens, with details on the left and the image on the right. However, on mobile screens, the ima ...

Automatically updating a database value in CodeIgniter after a countdown has expired

I am looking to automatically update a value in my MySQL database using CodeIgniter once a countdown timer reaches zero. However, I am struggling to figure out how to implement this. Here is an example: I have a database structured like this: [image lin ...

Adjusting the background opacity when the sidebar is open in a React + Typescript project

I am currently working on customizing a sidebar using the react-pro-sidebar library along with React and Typescript. The sidebar layout seems to be in order, but I am facing difficulty in adjusting the background color of the rest of the screen when the si ...

Tooltip positioned within a custom container using Material UI

Currently, as part of my Chrome extension development utilizing React and Material UI, I am implementing an inject page strategy. I have managed to set up a tooltip for the Fab button, but unfortunately, it appears outside the DOM of my extension. Upon ins ...

What are some ways to effectively utilize Selenium WebDriver and Appium together in a Cucumber test scenario?

I am facing a unique situation where I need to follow a specific process on a website (using Selenium) to create data, which is then transferred to a mobile app. After working on the mobile side (using Appium), I must return to the website to validate the ...

Tips for passing an array to a different function using Jquery

I need to pass an array to another function <div id="test"></div> <div id="test2"></div> <input type="button" value="chk" id="go" /> <script> $(function() { var c = 1; var i = 5; var dat ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

Exploring the topic of AngularJS unit testing and working with httpBackend timeouts

I have experience in the testing world, particularly with TDD using tools like mocha, sinon, chai, and nodejs. Recently, I've been finding AngularJS testing a bit challenging to grasp and implement. Currently, I am trying to test the simplest method ...

Tips for utilizing window.scrollTo in order to scroll inside an element:

I'm experiencing an issue where I have a vertical scrollbar for the entire page, and within that, there's an element (let's call it 'content') with a max-height and overflow-y scroll. The 'content' element contains child ...

What steps should be taken to retrieve the contents of a file that has been chosen using the browse

You have successfully implemented a browse button that allows the user to navigate the directory and choose a file. The path and file name are then displayed in the text element of the Browse button complex. Now, the question arises - how can I extract dat ...

Activate the preview mode by transmitting information between two controllers

I'm trying to set up a preview mode in one controller to show an image in another controller using an angular service. However, I'm struggling with the final step of getting the URL from the passed parameter into the ng-src in SideMenuCtrl dynami ...

implementing a calendar picker within a linked select dropdown using ajax

I'm currently working on fixing multiple errors, but one question that I have is why the datepicker doesn't pop up when I click on it. Which div should I be targeting for this functionality? <?php require '../common/pdo_connect.php' ...

Having trouble installing express and socket.io for my nodejs application

CONFG.JSON file { "name" : "realtimechatapp", "version" : "1.0.0", "private" : "false", "dependencies" : { "socket.io" : "2.3.4", "express" : "4.17.1" }, "author" : "coder123", } ERROR DETAILS 0 info it worked if it ends ...