Mastering the use of getText() in Protractor with Page Object Model in Javascript

Having trouble retrieving specific values from my page object. The getText() method is returning the entire object instead of just the text, likely due to it being a Promise.

I can provide my code if necessary, but I'm aiming to achieve something similar to this common online example for simplicity:

var AngularHomepage = function() {
  var nameInput = element(by.model('yourName'));
  var greeting = element(by.binding('yourName'));

  this.get = function() {
    browser.get('http://www.angularjs.org');
  };

  this.setName = function(name) {
    nameInput.sendKeys(name);
  };

  this.getGreetingText = function() {
    return greeting.getText();
  };
};
module.exports = new AngularHomepage();

Here's the modified spec file with added console logging:

var angularHomepage = require('../pages/AngularPage');
describe('angularjs homepage', function() {
  it('should greet the named user', function() {
    angularHomepage.get();

    angularHomepage.setName('Julie');
    var log = angularHomepage.getGreetingText();
    expect(angularHomepage.getGreetingText()).toEqual('Hello Julie!');
    console.log(log);
  });
});

The test passes successfully, however when logging the result, the entire object is displayed rather than just "Hello Julie!". This raises two main concerns:

a. Is the above method suitable for an "expect" statement with getText()? Despite the conflicting outputs, why does the test pass while the console reflects the entire object? Could it be related to the promise being fulfilled by the "expect"?

b. In the following snippet, I have updated the Page Object method to resolve the promise and accurately display "Hello Julie!" on the console. Although this approach works, utilizing "expect" directly within the method seems unconventional. Is there a better way to simply obtain the element's text without incorporating "expect" in the Page Object?

  this.getGreetingText = function() {
    greeting.getText().then(function (text) {    
      console.log(text);
      expect(text.toEqual('Hello Julie!'));
  });
    // expect is done, return not required.
    //return greeting.getText();
  };

Considering the perspective of a tester, comparing the actual text seems more accurate than the initial method. If using the first example proves acceptable and discourages placing "expect" in the Page Object, then that could be the way forward!

Answer №1

To solve this issue, simply convert your function into an asynchronous one and add the await keyword before assigning a value to your variable.

const message = await angularHomepage.getGreetingText();

By doing this, you will extract the content from the promise and save it in your variable for further use.

Answer №2

Employing a 'then' statement can help extract the text from a promise. This step is specifically required if you intend to record the text, whereas an expect statement has the capability to manage the .getText()

angularHomepage.getGreetingText().then(function(text){
    console.log(text);
    expect(text).toBe('Hello Julie');
});

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

Access the system by logging in with a stored Google account

I have experience integrating "Login via Google account" on various websites. However, some sites like Zomato always display the option to login via Google as soon as you open them. They even show a list of Google accounts that I have previously logged i ...

What is limiting me from utilizing the entire Google Calendar feed?

I currently have a public Google Calendar set up. My goal is to retrieve appointment data in JSON format from this calendar. When I utilize the following URL https://www.google.com/calendar/feeds/{calendar_id}%40group.calendar.google.com/public/basic?alt ...

Use a for loop to iterate through elements and retrieve input values using getElementById()

As I work through a for loop in JavaScript, I am utilizing the getElementById() method to fetch multiple input values. To begin, I dynamically created various input boxes and assigned distinct id's using a for loop. Subsequently, I am employing anoth ...

A guide on transferring received data from dataService within the parent component to the child component in Angular2

Within the context of my application, there exists a parent component named app-parent and a child component called app-child. In app-parent, I retrieve data from a DataService. @Component({ selector: 'app-parent', providers: [DataService] ...

How come it's not possible to modify the text of this button right when the function kicks off?

When I click a button, it triggers a JavaScript function. The first line of code within the function uses jQuery to change the HTML of the button. However, the button's text does not update in the browser until after the entire function has completed, ...

Ensuring accurate data entry through form validation within a table format

I'm working with a textbox that is part of a table column. My goal is to make sure the entire column is not empty when the Ok button is clicked. If you have any suggestions on how I can achieve this, please let me know. var formatTableMandatoryVa ...

Struggling to locate an nz-select form element in Selenium while attempting to click on it?

I am currently facing a challenge with automating the input in a form on a website, specifically with selecting a dropdown option. The website in question is: immosuche.degewo.de/de/properties/W1400-40660-0750-0902.html You'll need to click on "Kon ...

PHP: Extracting the selected value from a dropdown menu and incorporating it into an HTML link

Initially, I created a dropdown list Yet, there is uncertainty surrounding how to incorporate the selected choice (variable) into the input of the HTML <p style="text-align:center"> COVID-19 Checker</p> <br> <label for ...

Unable to retrieve information using the post method in Express framework

After creating a basic code to fetch data from the client, I am facing an issue where req.body.firstname is showing as undefined. Here is the code snippet: const express = require('express'); const app = express(); const body ...

Resize an image to fit perfectly within a material-ui grid

Is there a way to resize images within a grid layout without them getting cropped? Each image I try to fit into the top horizontal grid behaves differently due to varying dimensions. Instead of stretching and fitting into the container, the images end up b ...

Determine browser compatibility by evaluating the DOM Level

Can we easily determine which browser versions and above are compatible with a certain DOM level? ...

declaring a variable in JSP and incorporating it into jQuery

How can I retrieve the size of options in a route object and store it in a variable in JSP? I then need to access this variable in jQuery. Any suggestions on how to achieve this? JSP code : <%!int loopSize = routes.get(0).getOptions().size(); %> ...

Issues arising when trying to integrate Selenium's chromedriver with the at_exit function

Could the issue lie within my code or with Selenium, RSpec, etc.? In crafting my Cucumber tests, I encountered trouble shutting down and restarting the Chrome driver. Even after referencing a simple example in RSpec, the secondary driver fails to shut dow ...

How to implement jquery select functionality on clickable table rows?

I've come across a challenge while trying to implement clickable table rows with the jquery selectable function. Everything works perfectly fine with li elements, but I seem to hit a roadblock when using tables - the click event just stops working. Wh ...

What is the purpose of including an es directory in certain npm packages?

Why do developers sometimes have duplicated code in an es folder within libraries? Here are a few examples: https://i.stack.imgur.com/BWF6H.png https://i.stack.imgur.com/3giNC.png ...

Tips for refreshing information in the Angular front-end Grid system?

I am currently working with the Angular UI Grid. The HTML code snippet in my file looks like this. <div ui-grid="gridOptions"></div> In my controller, I have the following JavaScript code. $scope.values = [{ id: 0, name: 'Erik&a ...

Node receiving empty array as result after processing post request

My current task involves testing the post method on Postman. Strangely, every time I post the result it shows an empty array []. Upon further investigation by console logging on the node side, it also returns an empty array. CREATE TABLE users ( user_ ...

Having trouble sending specific data using the jQuery Form Plugin ajaxForm feature

Currently, I am utilizing two jQuery plugins: plupload and jQuery Form Plugin ajaxForm. Everything is functioning well except for one issue: I am unable to send the file.name (using ajaxForm) of a previously uploaded file with plupload. To elaborate more ...

Search for a DIV element within iMacro on a consistent basis

I recently started using iMacro and encountered an issue while recording a script that involved clicking on a pop-up when it appeared on the screen. The problem arose because the pop-up only appears when a new event is posted. Therefore, when I initially c ...

To enable Android permissions while testing with BrowserStack Automate using Selenium and Appium, simply click on the permission prompts

We are currently developing an automated test suite using BrowserStack Automate for our tests in Selenium with Appium. One particular test requires us to play DRM protected content which works fine on desktop platforms, but we are facing challenges testin ...