Issues with NightwatchJs arise when attempting to display element text, attributes, and values in the console

I'm facing some challenges with my nightwatch tests as I'm struggling to retrieve data from a webpage and display it on my console. Any guidance in the right direction would be greatly appreciated.

Every time I attempt to log the data to my console, it simply returns [object Object]. As a beginner in test automation, I haven't been able to find a solution by searching online. Below is the code snippet (testing site is Google's front page):

module.exports = {
  tags: ['google'],
  'Demo test Google' : function (client) {
client
  .url('http://google.com')
  .pause(500);
  var msg = "---> : ";

client.expect.element('body').to.be.present;

client.getText("#gbw > div > div > div.gb_7d.gb_R.gb_le.gb_ee > div:nth-child(1) > a", function(result) {
client.expect.element("#gbw > div > div > div.gb_7d.gb_R.gb_le.gb_ee > div:nth-child(1) > a").text.to.equal("Gmail");
console.log(msg.toString()+result);
});

client.getValue("#tsf > div.tsf-p > div.jsb > center > input[type='submit']:nth-child(1)", function(result) {
client.expect.element("#tsf > div.tsf-p > div.jsb > center > input[type='submit']:nth-child(1)").to.have.value.that.equals("Sök på Google");
console.log(msg+result);
});

client.end();
}
};

Answer №1

Recently, I came across a problem and found a solution by utilizing the 'textContent' method to capture the text within specific tags.

For instance, consider the following code snippet:

<div data-v-407a767e="" class="alert alert-success alert-styled-left alert-bordered text-center">
"Success! Check your email for the password reset link. "
<br data...>
<a data-v-407a767e="" class="alert-link">Go back to login.</a>
</div>

To extract the text, I used the following code:

client.getAttribute('selector', 'textContent', function(result){
        console.log("Value: ", result.value);
    });

For more information on using the textContent attribute, you can visit this link.

Answer №2

Today, I found myself spending countless hours trying to figure out the same issue. It seems like the documentation on the getText command might be misleading, or even incorrect. This is because it states that the return should be a string, but I am getting objects instead.

Check out this example code from nightwatchjs.org

The only way I have managed to obtain the string value of the element is by using the supposedly optional callback parameter.

Without the callback parameter, the value returned seems to be the browser object (basically, this, for making chained Command calls). If you echo this value, (and it's quite a bit of information), you will notice references to the browser Commands that are documented.

This discrepancy in return value and the documentation seems to be a recurring issue for many commands, including (as was the case for me today) getText.

If you happen to uncover more information later on that clarifies the apparent differences in return types (based on whether or not a callback parameter is utilized), please share it here. I am quite intrigued as well.

Answer №3

The explanation provided in the documentation lacks clarity. When a return value is received, it is in the form of an object, which can be accessed using the following code snippet:

self.getText('selectorvalue', function (result) {
   console.log('result: ' + JSON.stringify(result));
});

The returned object will contain various properties, with 'status' and 'value' being the most crucial ones.

If the 'status' in the result is -1, it indicates that the element was not found. Otherwise, the 'value' in the result should contain the text.

self.getText('selectorvalue', function (result) {
    if (result.status !== -1) {
        console.log('text: ' + result.text)
    }
});

To retrieve the text of existing elements and prevent test failures when elements do not exist, the following approach can be taken:

this.element('css selector', 'selectorvalue', function (present) {
     if (present.status !== -1) {
         self.getText('selectorvalue', function (result) {
             if (result.status !== -1) {
                 console.log('text: ' + result.text);
             }
         });
     }else{
         //don't try to get the text
     }
});

The 'this.element' function returns an object similar to 'getText', with a status of -1 for non-existent selector elements.

If an element is not found, the test does not fail.

It may be beneficial to define var self = this in commands and use 'self' instead of 'this'. In tests, 'client' or 'browser' can be used instead of 'this'.

Generally, the expectation is that the element will be present, so the test should fail if it is not. If this is not the desired behavior, the workaround mentioned above can be implemented.

Answer №4

An easy fix would involve extracting the required value from the object. Once you have the object, you can access its properties to find the one you need.

For instance, in the scenario you provided, you might consider implementing the following code snippet:

client.getText("your_element_locator", function(result) {
  expect(result.value).to.equal("Gmail");
  console.log(msg.toString()+result.value);
});

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 displaying the Primevue dialog modal in Vue 3?

I am using [email protected] and [email protected] Main script import { createApp } from 'vue' import App from './App.vue' import router from './router' import PrimeVue from 'primevue/config'; import &apos ...

Obtain the ending section of a URL using JavaScript

Is it possible to extract the username from a URL like this example? I'm interested in seeing a regex method for achieving this. The existing code snippet only retrieves the domain name: var url = $(location).attr('href'); alert(get_doma ...

Encountering a "Value cannot be null" error while using VS2015 Coded UI for Cross Browser testing with Chrome

While executing a Coded UI test against Chrome, the cross-browser console appears and the Chrome browser window pops up (without displaying the webpage), but then I encounter an exception: System.ArgumentNullException: Value cannot be null. Parameter n ...

Adjust the value of a variable within a module using Angular JS

Within my module, I have the code below: var mod; mod = angular.module('ajax-interceptor', []); mod.config(function($httpProvider) { $httpProvider.interceptors.push(["$q", function($q, dependency1, dependency2) { return { ...

Implementing a new click method in JAVA Selenium WebElement class

Is it considered a best practice to modify the WebElement click() method to include some wait functionality? There are instances where I need to click a button, but in some cases, the button may not have loaded yet, so I added a wait to verify if the eleme ...

Spinning item using a randomized matrix in Three.js

I'm in the process of creating a 3D die using Three.js that will rotate randomly when clicked, but I'm struggling to update the axis values properly. Here's where I'm currently at: <style type="text/css" media="screen"> html, ...

Activate a link, launch a pop-up window, and navigate to the link within the pop-up

I have an unusual idea I'm working on. Let me explain the situation first, and then I'll outline the step-by-step process I want to follow. I currently have a list of items inside a <ul>. Whenever I click on one of these items, I want a mod ...

Using Typescript to establish a connection between ngModel and an object's property

Let's talk about how we can dynamically bind an input to an undefined property in an object. For example, we have an object named user: let user = {}; How can we bind an input to a property that doesn't exist yet? Like this: <input [(ngMode ...

When you click on the column header to sort, the corresponding column row changes color in JavaScript

https://i.sstatic.net/4ELuv.jpg When a user clicks on a column to sort, the color of the column changes or highlights the row. In my tablesorter with ascending and descending sorting capabilities, I want the sorted column to change colors for better visib ...

What is the best way to determine if an element exists?

Is there a way to determine if an element exists before using the attribute "for" or checking for a label? def getidByLabel(self,driver,target_type,target_label,row_position): if target_type == 'form': attr_id = driver.find_element_b ...

Tips for updating a React state while using the history API

In an effort to simplify and stay focused on the problem, I recently wrote a brief piece of code. Within this code, there is a component containing a Dialog that plays a role in a commercial process. This Dialog allows users to input information such as no ...

Arrange a JSON array by searching texts initially, followed by sorting the remaining results in alphabetical order

I am looking to sort a JSON array in JavaScript based on a search text. The sorting should prioritize items that match the search text at the beginning of their value, followed by alphabetical sorting for the remaining results. Even if the search text is f ...

Display the hidden div element when clicked

In my code, I have two div elements as follows: <div class='staticMap'></div> <div class='geolocation-common-map'></div> Initially, the 'geolocation-common-map' div is removed using jQuery when the pa ...

Using Laravel Blade Variables in JavaScript Code

Trying to access a variable within blade syntax has posed a challenge for me: success: function(resp) { console.log(resp) var MsgClass = 'alert-danger'; $("#overlay").hide(); ...

I require assistance in displaying a dynamic, multi-level nested object in HTML using AngularJS

I have a complex dynamic object and I need to extract all keys in a nested ul li format using AngularJS. The object looks like this: [{"key":"campaign_1","values":[{"key":"Furniture","values":[{"key":"Gene Hale","values":[{}],"rowLevel":2},{"key":"Ruben A ...

NextJS: When attempting to serialize the `function` as JSON, an error occurs as it is not a JSON serializable data type

In my Firestore database, I have a collection named "mentor" that contains documents with three fields: "name", "email", and "linkedin". My goal is to fetch all the documents from this collection and pass them as props so that I can render their fields on ...

Error receiving parameter in express route callback function

At the moment, I have been working with a number of routes in Express. Some routes are quite lengthy and tend to look like this: router.get('/api/comments', function(req, res, next){ Comment.find({"user": req.payload._id}).exec(function(err,co ...

Mastering the art of debugging a mongoose action in node.js

I am utilizing mongoose for connecting my node.js app with mongoDB. However, I am facing an issue where the database does not get updated when I create or update a model instance. How can I effectively debug and identify what goes wrong in the create or up ...

Executing a PUT XMLHttpRequest request results in an empty response being logged to the

I've been struggling to send a PUT request using XMLHttpRequest, but I keep getting an empty response. I'm using JS for the front end and nodejs for the backend. Even though the network section in the dev tools shows that the PUT request is okay, ...

Can you explain how to convert a 32-bit floating point number from a Buffer to a JSON string in NodeJS while maintaining the original precision?

Given a buffer with single precision float numbers (32 bits, little endian), the goal is to create a JSON string holding those numbers while maintaining their original values without any loss of precision. The challenge lies in the fact that when a value ...