Extract a value from a promise nested within Webdriver

My goal in the test code is to achieve the following:

it('Updates label text', function(done) {
   page.testLabelText();
   assert.equal(page.testLabelText().pageLabel, page.testLabelText().iFrameLabel);
   done();
});

In my page object, here is testLabelText();:

page.testLabelText = function () {
    var pageLabel = function () {
        return driver.findElement(By.css('#element')).getText().then(function(text) {
            return text;
        });
    };
    var iFrameLabel = function () {
        return driver.findElement(By.css('#element')).getText().then(function(text) {
            return text;
        });
    };
    return {
        pageLabel: pageLabel(),
        iFrameLabel: iFrameLabel()
    };
};

However, when printed to the console, this returns 'Undefined'...I am new to Javascript and although I have been able to do this in regular javascript, all my attempts with Selenium WebdriverJS promises have failed...

Answer №1

Your assert.equal() function is currently comparing two separate promise objects, which will never return true. To better understand why this is the case, let's break it down step by step. In order to compare the values correctly, you must extract the values from both promises after they have been resolved.

Simply calling page.testLabelText(); without assigning or referencing the return value does not accomplish anything significant as it just returns an object.

page.testLabelText().pageLabel and page.testLabelText().iFrameLabel, when called individually, both return promises.

Since these are distinct promise objects, your current use of assert.equal() will not yield the correct comparison result.

If you intend to compare the values from these promises, you can use the following code snippet:


var obj = page.testLabelText();
Promise.all([obj.pageLabel, obj.iFrameLabel]).then(function(results) {
    assert.equal(results[0], results[1]);
    done();
});

Answer №2

To tackle the issue, I opted to implement an assertion library capable of handling promises within tests, as conventional async asserts would not suffice. The tool I utilized was Chai as Promised.

The requisites included:

chai = require('chai'),
chaiAsPromised = require("chai-as-promised"),
should = chai.should();

By adding chai.use(chaiAsPromised); in mocha's before hook, I could proceed to script

it('Updates label text', function() {
  var label = FormsPage.testLabelText();
  label.labelHeading.should.eventually.contain(label.userInput);
});

A helpful blog post on this topic can be found here

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

When data is present, the AngularJS scope array remains hidden from view

Whenever I try to populate a scope array property by calling an AJAX service, the data gets filled in as expected. However, I am faced with the issue that I have to interact with another control or click somewhere on the page to actually display the array. ...

What causes the discrepancy between $route.current.params and $routeParams?

My attempt to code an Angular Route for the controller to catch a parameter didn't go as planned. Here is my configuration: .config(function ($locationProvider) { $locationProvider.html5Mode({ enabled: true, requi ...

Unable to find the element using the XPath locator that contains the specified text

Hello there, talented wizards of Stack Overflow! I'm currently attempting to retrieve an array of elements that contain a specific text using xpath. The xpath element in question is: //*[@id="produtoNCM_50"] There are 27 sequential elemen ...

Tips for implementing dynamic typing with Prisma

Encountering the error "this expression is not callable" while using the findUnique method with dynamic models. How can this type error be resolved? export const isFound = async ( model: Prisma.ModelName, id: string | number, idName: string ): Promis ...

Is there a way to transfer table row data to another table by simply clicking on the corresponding checkbox in the same row?

I'm working with a table that includes 4 fields: service, amount, tax, and action. My challenge is to have the data from any row in the first table added to a second table when its checkbox is selected. The second table should have the same fields a ...

Get access to a JSON key using forward slashes in Node.js

I'm facing an issue with accessing a property in an object that contains forward slashes. Specifically, I need to access the child key pattern. Unfortunately, my attempts so far have been unsuccessful. Please provide a solution to access the pattern p ...

Implement a new method called "defer" to an array that will be resolved at a later time using Promise.all()

I need to manage a queue of DB calls that will be executed only once the connection is established. The DB object is created and stored as a member of the module upon connection. DB Module: var db = { localDb: null, connectLocal: (dbName) => { ...

Calculate the total duration between two times and, if the difference is more than 10 minutes,

I need to calculate the duration between two dates, start_time and end_time. If the minutes component is greater than 10, I want to round up the hours component. For example: 12 minutes different - rounded up to 1 hour 1 hour 31 minutes difference - roun ...

Is there a way to utilize useEffect for detecting changes in screen width?

One challenge I am facing while using React is dealing with a canvas that varies in size and shape based on the screen dimensions. To draw something on this canvas, I find myself having to set specific dimensions for each different screen size. const [scre ...

What is the method to group a TypeScript array based on a key from an object within the array?

I am dealing with an array called products that requires grouping based on the Product._shop_id. export class Product { _id: string; _shop_id: string; } export class Variant { variant_id: string; } export interface ShoppingCart { Variant: ...

P5: Exploring the Intersection of Arrays

I am faced with the challenge of extracting values from one array based on indices from another array. I have successfully loaded two text files using loadStrings and stored the data in two separate arrays. The lengths of the two text files are different - ...

What do you think is the root cause of the grey streak?

I've implemented an image slideshow on my website: However, I'm facing an issue with a grey line appearing under the annotation. Here is an example: Below is the code snippet: $(function(){ $('#slides').slides({ ...

Adjust the height to match the shortest sibling child div height

In my layout, I have multiple rows with each row containing multiple columns. Within each column, there is a div and a paragraph - the div contains an image. My goal is to set the div with the class cover-bg to the lowest height of cover-bg in the same row ...

Altering the status of a property in an object, at a specific position within a collection of objects, contained within another object?

Currently using React and having some trouble with the setState hook to update a value deep within an object structure ...

Troubleshooting issue in App component while utilizing React-Redux's 'connect' function

Upon attempting to utilize the connect() function provided by react-redux, I encountered the following error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the r ...

Can a JavaScript framework be created to ensure all browsers adhere to standards?

As someone who isn't an expert in JavaScript, I wonder if it's feasible to create a comprehensive embeddable JavaScript file that ensures all browsers adhere to standards. Could there be a compilation of known JavaScript hacks that compel each br ...

Click event from Angular Material menu is triggered twice on mobile devices

After implementing a basic angular material side menu from the demo, I noticed that all click events are being fired twice on the entire page when viewed in mobile browsers. This issue can even be replicated in the Chrome emulator. (To reproduce, enable th ...

What is the best way to organize a flatlist for rendering?

I'm struggling with separating some flat-lists into different components. How can I arrange the rendering of the flat-list like the sample form (Picture "Sample UI")? I've tried, but it's not working correctly as it renders flat list A first ...

Navigating Crossroadsjs Routing: A Beginner's Guide

After exploring various resources to understand how crossroads works, I stumbled upon a question on Stack Overflow that resonated with my struggles. However, despite spending hours trying to implement it, nothing seems to be working. The documentation on i ...

The issue arises when attempting to populate the Facebook login window after clicking the 'like' button in Selenium webdriver

Hey there, I need help with a HTML snippet. I'm trying to click on the Facebook icon and open a popup window, but when I use Selenium's click action, no error is displayed, yet the popup window doesn't appear. If you have any solutions, ple ...