I'm struggling to figure out why I can't set an object value to a specific variable in Nightwatch.js

Currently, I am in the process of creating a test script using Nightwatch.js. Before clicking on an element, I am extracting the text within it and isolating the value field to assign it to an externally declared variable. However, I am encountering an issue where the value is not being assigned within the callback function.

Here is the snippet of code that I am working with:

var meeting = "";

module.exports = {
    'step 1: open event page': function (browser) {
        browser
            .url('http://example.com')
            .waitForElementVisible('.navigation-list-item:nth-of-type(2)', 20000)
            .getText('.navigation-view > .list-container > .navigation-list-item:nth-of-type(2) > a > .list-content > .list-body', function (location) {
                meeting = location.value;
            })
            .pause(3000)
            .click('.navigation-view > .list-container > .navigation-list-item:nth-of-type(2) > a > .list-content > .list-body')
            .pause(3000)
            .assert.containsText('.ncb__title', meeting);
    }
}

I would greatly appreciate any assistance or insights on this matter. Thank you!

NOTE: The actual URL of the site under testing has been excluded for confidentiality reasons.

Answer №1

Have you checked if your value is being assigned properly? Try printing the meeting variable after assigning it in the callback function. Give this a shot:

.getText('.navigation-view > .list-container > .navigation-list-item:nth-of-type(2) > a > .list-content > .list-body', function (location) {
                   meeting = location.value;
                  console.log(meeting);

            })

If the value is being printed, then that may not be the issue. Since I'm new to JS and not sure of the reason, here's a workaround that worked for me:

.url(function(){
    this.assert.containsText('.ncb__title', meeting)
  })

I hope this solution helps you out.

Answer №2

The issue at hand arises from Nightwatch operating asynchronously. As a result, by the time you reach the callback where you set the getText value, Nightwatch has already progressed to the step where you are utilizing it to verify the outcome.

To tackle this problem, it is advisable to use steps to clearly separate these actions.

For instance:

// At the beginning of your test, declare your variable globally
var myTestVar = 'foo';

module.exports = {
    // While navigating in an isolated step isn't mandatory, 
    // it ensures that all other operations come after navigation.
    'Step One: Visit the page': function (browser) {
        browser
          .url('http://example.com')
          .pause(2000);
    },

    'Step Two: Retrieve information': function (browser) {
        browser.getText('@element', function(result) {
            // Set the value of the result within the callback function
            // Assuming the text of @element is 'bar' for this test
            myTestVar = result.value;
        });
        // Due to nightwatch's asynchronous execution, this will display 'foo'
        console.log(myTestVar);
    },

    'Step Three: Display the result': function (browser) {
        // This section will only execute once Step Two is finished
        // Thus, it will display 'bar'
        console.log(myTestVar);
    };

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

Objects being collected as arrays of arrays in garbage collection

I recently came across an article stating that a simple delete is not sufficient to release memory allocated for an object. In my current scenario, I have an Object with several subOjects structured like this: MyObject[idx]['foo']. Is there a me ...

"What might be causing the error 'cannot access property 'top' of undefined' while trying to read

My website has a sticky navbar fixed at the top, and this is the structure of my sticky navbar: $(function() { $(window).scroll(function() { if ($(window).scrollTop() > $(".b").offset().top + $(".b").height() && $("input").val() == "") { ...

The <a> tag does not lead to a different webpage and cannot be clicked on

I have developed a web component that includes a method to generate a copyright string: '<p>Copyright © 2020 John Doe<a href="https://www.example.com">. Terms of Use</a></p>' After creating the string, I conver ...

How can parameters be implemented in Angular similar to NodeJs Express style?

Is there a way to implement a Parameter in Angular routes that resembles the NodeJs style? I have a route like **http://myhost.domain.com/signin**" and I want to pass an id for the signin request. Although I can achieve this using **http://myhost.doma ...

When trying to run the "npm start" command, I encountered a syntax error that specifically mentioned the use of

Every time I attempt to run the npm start command, I encounter the following error: I have followed the steps provided in this link: https://github.com/kriasoft/react-starter-kit/blob/master/docs/getting-started.md Could you please advise on how to resolve ...

Tips for choosing a loaded element using the jQuery load() method

I am currently facing a challenge with the following (here is a snippet of code to illustrate): <div id="container"></div> <script type="text/javascript"> $('#container').load('content.html'); $('.eleme ...

Transferring information from a Jade file to a Node.js server

I'm currently working on creating a data object within my Jade view page that will be used in my server-side JS. The data object involves dynamic HTML generation that inserts input boxes based on user input. function addDetail() { var det ...

Does Vuejs emit an event when a specific tab becomes active in boostrap-vue?

I am looking for a way to display and hide a section on my page when a specific tab is active, and close it when the tab is inactive. I have tried using the forceOpenSettings and forceCloseSettings methods for opening and closing the div. Is there an event ...

Is it possible to create a unique texture transition effect in three.js?

Currently, I am working on creating a model viewer in three.js using opengl. One of the key features I am trying to implement is the ability to dynamically change textures while the model is running. So far, I have managed to achieve this functionality, ...

The screen-responsive navigation bar is experiencing functionality issues

I am facing an issue with my navigation bar on both desktop and mobile. When I maximize the window while the mobile navbar is open, it disappears as expected but the desktop navbar does not appear. I am using a bootstrap template and I am unsure if solving ...

Running a function in NodeJS and sending a response to the client: A step-by-step guide

Currently, I am working on encrypting some text for an HTML project. The encryption code I have requires a node.js server to run the function, but unfortunately, I am unable to execute it in my original HTML code. As a beginner in JavaScript, I find it cha ...

Exploring Portals in ThreeJs

Hey, has anyone successfully created a portal effect in ThreeJS? I'm interested in experimenting with impossible architectural designs for my VR thesis. Specifically, I'm attempting to construct a small square house where looking through the doo ...

Oops! SAPUI5 is encountering an issue with reading property '0' of undefined

Is there a possibility of encountering multiple errors leading to this specific error message? https://i.stack.imgur.com/RpWhw.png Despite searching online, it appears that the error occurs in the JavaScript file when getelementbyid returns null. However ...

Pass data as json from javascript to php

After users perform actions on a page and click "next," the goal is to redirect them to a PHP file named "Step2.php" along with specific JSON data. The constructed JSON string is as follows: [{"name":"IMG_20130726_182336.jpg","size":2280709,"type":"image ...

Creating Pop-up Dialog Boxes in WebForms Using jQuery

I have implemented a Plugin in Webforms using jQuery UI dialog. Since I have a Content Place holder on my Form, I had to modify the code as shown below: <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> <link rel="stylesheet" ...

Transforming DayOfYear data in Javascript to utilize with Flot

Attempting to utilize the flot jQuery library for a display, but running into an issue with the X Axis showing dates. The data being received is in DayOfYear format instead: var data = [[192,6.9],[191,49.52],[190,2],[189,0], etc...] Numbers like 192, 19 ...

error message: "The mtlLoader Module does not have the export named 'MTLLoader'"

I am struggling with getting the mtlLoader module to work in three.js. I am a beginner and I am trying to import the mtlLoader module from the latest three.js-master repository on the official website. However, I keep encountering this error message when I ...

Can we determine if a user's operating system has disabled animations?

In my frontend project with React, I am incorporating an animation within a component. However, I want to cater to users who have disabled animations in their settings by replacing the animated content with a static image. Is there a method to detect if ...

Having trouble connecting to the Brewery API, could use some guidance from the experts (Novice)

I'm currently facing some difficulties connecting to a brewery API (). I am developing a webpage where users can input the city they are visiting and receive a list of breweries in that city. As someone unfamiliar with APIs, I am unsure about the nece ...

Looping through a sequence of asynchronous tasks, utilizing the async/await syntax, writing data to

I'm currently working on a script to download pdf files from a specified URL and save them to my local disk. However, I have encountered an issue where I need each file to be downloaded one at a time with a one-second delay in between (to ensure that ...