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

Iterating over an array and displaying elements on the webpage

Struggling to access an array and loop through it, but only able to print out one element instead of all. Need a hint on how to solve this issue. See my code below: let toppingsCount; const burger = document.createElement('div'); const toppingsD ...

Click on the link or tab to update the marker location on the Google Map

Can you click on Tab 2 to change the marker/location, and then go back to Tab 1 to switch it back to the original location? [Links to Fiddle] http://jsfiddle.net/ye3x8/ function initialize() { var styles = [{ stylers: [{ saturati ...

Steps to Extract the key value from the parseJson() function

Could someone assist me in retrieving the value of the "id_user" key from the script provided below? JSON.parse({ "data": [ { "id_user": "351023", "name": "", "age": "29", "link": "http://domain. ...

Why is applying CSS on an li element using .css() in JQuery not functioning?

Hey there! Could you please review my code? I'm attempting to add a top position to the <li> element using a variable in jQuery, but I'm not sure how to do it. Here's the code: <script> $(document).ready(function(){ ...

Guide on incorporating a customized HTML tag into ckeditor5

Can someone help me with integrating CKEditor and inserting HTML tag of a clicked image into the editor? I've tried different solutions but haven't been successful. I understand that doing this directly in CKEditor may not be secure. This is a V ...

The Angular bootstrap datetimepicker doesn't support disabling past dates

Has anyone successfully disabled past dates on an angular bootstrap datetimepicker before? I've tried using the date-disabled attribute, but I can't seem to get it to work. <datetimepicker class="calendar-format" data-ng-model ...

Using setTimeout in Node.js

I've been struggling to find a solution for slowing down the timeout in my code. The issue is that it runs too quickly, and I can't seem to figure out how to adjust it using Request. Everything else in the code works perfectly. var Scraper = fun ...

Engaging with website components that modify HTML content values

I'm using Selenium to automate the process of clicking through parking garage markers on the website http://seattle.bestparking.com/. The goal is to open the pop-up info window for each marker and then extract information from the "rate" page in the p ...

Issue with Vue JS: e.preventDefault not functioning correctly when using Axios

I am facing an issue in my Laravel project where I have implemented a method in the Vue instance to validate resource availability upon form submission. The validation is done through an AJAX call using axios, and if any resources are unavailable, I receiv ...

Guide to converting raw Mysql fields into objects using Node.js

I have written a code to retrieve all the rows from the article table in MySQL, but I would like to represent this data in object and array format so that I can send it to endpoints. app.get('/article' , function(req , res){ var connec ...

Cracking the code of the @ symbol within this particular context

https://github.com/react-dnd/react-dnd/blob/master/examples/04%20Sortable/Simple/Card.js I'm trying to comprehend the significance of the @ symbol in this example. This is meant to be a straightforward drag and drop demonstration, but the implementa ...

What is the best way to save a large quantity of objects to a server using ajax and php?

Imagine a scenario where I have a page containing 100 objects, each around 700 bytes when converted to json format. When it comes to saving these objects to the php based controller, there are several options available to me. Option 1: For each object ( ...

Creating dynamic web content using KaTeX and Node.js

When I attempt to display a complex formula using HTML and CSS, I encounter difficulties. Instead of the desired output, my screen is filled with confusing unicode characters. To resolve this issue, I decided to use KaTeX. I downloaded KaTeX into the dire ...

Guide on creating my inaugural HTML embeddable widget?

A client recently requested me to create a JavaScript (MooTools)/HTML/CSS/PHP based game as a deployable widget. This will be my first time developing a widget, so I am seeking advice and insights to help me navigate any potential challenges from experie ...

Using the Unsigned Right Shift Operator in PHP (Similar to Java/JavaScript's >>> Operator)

Before marking this as a duplicate, please take a moment to read the information below and review my code * my updated code! The issue I am facing is that I need to implement Java/JavaScript '>>>' (Unsigned Right Shift / Zero-fill Right Shift) ...

Production build encountering unhandled TypeError in proxy

One day, I decided to tweak MUI's styled function a bit, so I came up with this proxy code: import * as muiSystem from '@mui/system'; type CreateMUIStyled = typeof muiSystem.styled; type MUIStyledParams = Parameters<CreateMUIStyled>; ...

Error: Node-Sass - Unable to download win32-x64-57_binding.node

Currently in the process of getting a retired colleague's program up and running, but when attempting to execute meteor run I encounter this error. While loading package materialize:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Transferring information to a partial view using a jQuery click event

In my Index view, there is a list of links each with an ID. My goal is to have a jQueryUI dialog box open and display the ID when one of these links is clicked. Currently, I am attempting to use a partial view for the content of the dialog box in order to ...

Integrating tilt and zoom functionality on a web page based on mouse movements

While browsing through some messages on chat, I came across something interesting: I noticed that as I moved my mouse left or right, the content would tilt in that direction, and when moving up and down, the content would zoom in or out. It was a really c ...

Setting URL parameters in a POST request: A guide

Currently, the data in question is structured as JSON within this code snippet. However, I've received feedback indicating that it should actually be implemented as URL parameters. I'm currently facing some difficulties with modifying this to fit ...